Portuguese (Brazil) 1.0.0: run 2026-11-13-1728 + guards; gold 416/183/4/0, Tatoeba 0.10%
Browse filesFiles changed (14)
- LICENSEAdded+202
- NOTICEAdded+9
- README.mdAdded+247
- config.jsonAdded
- gector-guards.jsonAdded+159
- gector-meta.jsonAdded+41
- language-rules.jsonAdded+7
- model.onnxAdded+3
- quickstart.ipynbAdded+118
- quickstart.pyAdded+236
- tokenizer.jsonAdded
- tokenizer_config.jsonAdded+15
- verb-form-vocab.txtAdded
- vocab.txtAdded
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.123456789Proofbird GECToR grammar model (Portuguese, Brazil)Copyright 2026 Patrick Andrew Hartnett
This product includes software developed by Patrick Andrew Hartnett for Proofbird(https://proofbird.app). Source: https://huggingface.co/proofbird/gector-bert-pt-br
Based on neuralmind/bert-base-portuguese-cased (BERTimbau) by Fábio Souza, Rodrigo Nogueiraand Roberto Lotufo, NeuralMind (MIT licence), and the GECToR tagging scheme(Omelianchuk et al., 2020; Apache License 2.0).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247---license: apache-2.0language:- ptbase_model: neuralmind/bert-base-portuguese-casedpipeline_tag: token-classificationlibrary_name: onnxtags:- grammatical-error-correction- gector- onnx- on-device- brazilian-portuguesedatasets:- wikimedia/wikipedia---
# Proofbird Grammar — Portuguese (Brazil)
`gector-bert-pt-br` · on-device Brazilian Portuguese grammar correction
[](https://huggingface.co/spaces/proofbird/try-grammar)
**Try it in your browser:** type a sentence and see the corrections. The model runs on your own computer; nothing to install, and your text never leaves the page.
**Version 1.0.0** · run `2026-11-13-1728` · tag [`v1.0.0`](https://huggingface.co/proofbird/gector-bert-pt-br/tree/v1.0.0), the files the Proofbird app downloads. Pin it with `revision="v1.0.0"`. Versions: a change to the model's design (encoder, inputs, outputs) raises the first number, a new training run or changed guards and rules the second, card or metadata fixes the third.
A GECToR-style sequence tagger for Brazilian Portuguese grammatical error correction, exported to ONNX (fp32) to run onthe CPU. It is the on-device grammar model of [Proofbird](https://proofbird.app), a writing assistant for Windows, and itis published here so anyone can inspect what runs on their machine. European Portuguese gets its own model, trained onEuropean text.
GECToR does not rewrite text. For each token it predicts one edit tag (keep, delete, replace with a word, append aword, change case, change a verb form), and the edits are applied and the sentence re-tagged up to five times. Thetagger only proposes local edits; it never paraphrases.
## Quick start
[](https://colab.research.google.com/#fileId=https%3A//huggingface.co/proofbird/gector-bert-pt-br/blob/main/quickstart.ipynb)
No API key, no GPU. One file, [`quickstart.py`](quickstart.py), downloads the model and runs it with ONNX Runtime.
```bashpip install onnxruntime tokenizers huggingface_hub```
```pythonimport importlib.utilfrom huggingface_hub import hf_hub_download
spec = importlib.util.spec_from_file_location("quickstart", hf_hub_download("proofbird/gector-bert-pt-br", "quickstart.py"))quickstart = importlib.util.module_from_spec(spec)spec.loader.exec_module(quickstart)
model = quickstart.Gector("proofbird/gector-bert-pt-br")corrected, suggestions = model.correct("A casa são muito bonito.")print(corrected)print(suggestions)```
```textA casa é muito bonita.[{"start": 7, "length": 3, "original": "são", "replacement": "é"}, {"start": 17, "length": 6, "original": "bonito", "replacement": "bonita"}]```
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 "A casa são muito bonito."` prints every step below.
## What it corrects
Gender and number agreement (articles, adjectives, participles, nouns after determiners), subject-verb agreement(`Os meninos come` → `comem`, `Eles tem` → `têm`), article gender (`um casa` → `uma casa`), contractions(`de o` → `do`, `em a` → `na`, and a preposition written twice), the crase (`Vou a praia` → `à praia`), accentsand diacritics (`esta cansada` → `está cansada`, `voce` → `você`), the plural of `-ão` nouns (`informaçãos` →`informações`), capitalisation at the start of a sentence, and everyday-register errors in questions, imperatives andthe first and second person.
It is written for Brazilian Portuguese: `você`, `ônibus`, `fato`, `contato` and `estar` + gerund (`está estudando`) arecorrect to it. It leaves European Portuguese spelling and usage alone (`facto`, `equipa`, `autocarro`, `está atrabalhar`) rather than changing it.
## How it was trained
- **Base encoder:** [`neuralmind/bert-base-portuguese-cased`](https://huggingface.co/neuralmind/bert-base-portuguese-cased) (BERTimbau, MIT). A tagging head (5 000 edit labels) and an error-detection head sit on top.- **Data: synthetic only.** 2 750 000 sentences from Portuguese Wikipedia ([`wikimedia/wikipedia`](https://huggingface.co/datasets/wikimedia/wikipedia), `20231101.pt`), keeping only articles whose spelling and usage mark them as Brazilian, and 250 000 sentences from [Tatoeba](https://tatoeba.org) (Brazilian or unmarked) were corrupted by hand-written Portuguese error rules; about 10% stay clean, so the model learns to leave correct text alone. 200 000 additional template sentences teach patterns Wikipedia rarely contains (first and second person, questions, imperatives, long-distance agreement).- **No learner corpora** and no non-commercial data in the fine-tuning. No user text was used.- One epoch (93 918 steps, batch 64, learning rate 3e-5) on one NVIDIA L4. Run id `2026-11-13-1728`.
## How it was measured
| Check | Result ||---|---|| Gold set (603 hand-written sentences: 420 with one error each, 183 correct, 53 of them in Brazilian-only forms) | **416 fixed, 183 left alone, 4 missed, 0 made worse** || False alarms on 4 000 everyday Tatoeba sentences (Brazilian or unmarked, held out from training) | 4 changed (0.10%); 1 of them corrects an error in Tatoeba's own text || Stability: the gold re-run with one extra token in front of each sentence | 0 sentences change result (the 4 capitalisation rows change by construction and are not counted) |
The scores are with the apply-side guards in `gector-guards.json` (below). The model was trained for precision: amissed error costs less than a wrong correction. The misses: an adjective after a plural verb with no subject in view(`Estamos muito cansado`, held on purpose: the verb fixes the number but not the gender) and a verb two clauses away fromits subject (`… e os irmãos dela está jogando bola`). Known limits: a noun after a numeral can stay singular (`doisgato`), and on its own the model can write a non-word for an adjective ending in `-m` (`muito bom` → `boms` after aplural subject); the Proofbird app holds every non-word back.
The Tatoeba changes: one correction of Tatoeba's own text (`Alguem` → `Alguém`) and three false alarms: `cheguei a casa`→ `à casa` (European usage), `um caixa automático` → `automática` (`caixa` is masculine here) and the European slang`está bera` → `bero`. It has not been measured on learner essays.
**The guards.** `gector-guards.json` holds back edits we measured as wrong in a known shape. They run in the Proofbirdapp (not in `quickstart.py` or the demo) and are part of every score above. Among them: a change of the verb's personneeds a subject for the new person in the sentence; `o/a estudante`, `o/a colega`, `a melhor` take either article; `é`never becomes `e` (`A guerra é o inferno`); `Está tarde` stays (it is a sentence, like `Esta tarde`); the crase before afeminine noun stays (`à chave`, `à cabeça`); `dele`/`deles` follow the owner, which the sentence may not show; `por o`after `vou`, `quero`, `posso` and similar verbs is `pôr`, not `pelo`.
## Files
| File | What it is ||---|---|| `model.onnx` | The tagger (fp32, opset 17). Inputs `input_ids`, `attention_mask`; outputs `logits_labels` [1, T, 5000] and `logits_d` [1, T, 2]. || `config.json` | The edit-label vocabulary (`id2label`). || `vocab.txt`, `tokenizer.json`, `tokenizer_config.json` | The base encoder's WordPiece tokenizer. || `gector-meta.json` | Export facts: encoder, tokenizer family, decoding defaults, run id, version. || `gector-guards.json` | Apply-side guards: rules that hold back an edit the model gets wrong in a known way (for example `é` → `e`, which turns the verb into "and"). Part of the measured result. || `language-rules.json` | Language facts the runtime needs (sentence-final punctuation handling). || `verb-form-vocab.txt` | The Portuguese verb-form table for the `$TRANSFORM_VERB_*` tags (428 verbs, present tense, built for this model). || `quickstart.py` | A complete Python runner: download, tokenize, run, decode, apply, suggestions. See *Quick start*. || `quickstart.ipynb` | The same, as a notebook (the *Open in Colab* button). |
The Proofbird app runs the same algorithm in C# with ONNX Runtime; the files are standard, so any GECToR-styledecoder can use them.
## How it works, step by step
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_isto`, `$REPLACE_abrem` 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.
**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): `A casa são muito bonito`.
**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.
```textwords $START A casa são muito bonitotokens [CLS] A casa são muito bonito [SEP]input_ids [101, 177, 1105, 453, 785, 22003, 102]attention_mask [1, 1, 1, 1, 1, 1, 1]```
Two inputs, both whole numbers (int64), shape `[1, 7]`: one sentence of 7 tokens.
**3. The response.** Two outputs (float32): `logits_labels` `[1, 7, 5000]`, a score for each of the 5 000 edits at every token, and `logits_d` `[1, 7, 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.
**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.
*Pass 1:* `A casa são muito bonito`
| Word | Wrong | Chosen edit | Probability ||---|---|---|---|| $START | 0.1% | $KEEP | 99.9% || A | 0.0% | $KEEP | 100.0% || casa | 0.0% | $KEEP | 100.0% || são | 98.4% | **$TRANSFORM_VERB_P3P_P3S** | 98.4% || muito | 0.0% | $KEEP | 100.0% || bonito | 13.6% | $KEEP | 86.7% |
→ `A casa é muito bonito`
*Pass 2:* `A casa é muito bonito`
| Word | Wrong | Chosen edit | Probability ||---|---|---|---|| $START | 0.0% | $KEEP | 100.0% || A | 0.0% | $KEEP | 100.0% || casa | 0.0% | $KEEP | 100.0% || é | 0.0% | $KEEP | 100.0% || muito | 0.0% | $KEEP | 100.0% || bonito | 100.0% | **$TRANSFORM_SUF_o_a** | 99.7% |
→ `A casa é muito bonita`
*Pass 3:* `A casa é muito bonita`
| Word | Wrong | Chosen edit | Probability ||---|---|---|---|| $START | 0.0% | $KEEP | 100.0% || A | 0.0% | $KEEP | 100.0% || casa | 0.0% | $KEEP | 100.0% || é | 0.0% | $KEEP | 100.0% || muito | 0.0% | $KEEP | 100.0% || bonita | 0.0% | $KEEP | 100.0% |
→ `A casa é muito bonita` — no change, so it stops.
**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.
**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):
- `keep_confidence` adds a bonus to `$KEEP` before choosing: higher means fewer, safer edits.- `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 (`A casa é muito bonita.`): the model is 98.4% sure one word is wrong.
## What Proofbird adds
`quickstart.py` is the model on its own. The [Proofbird](https://proofbird.app) app runs the same algorithm in C# and adds:
- **Guards**: per-language rules that hold back edits we measured as wrong in a known shape. `gector-guards.json`, in this repository, lists which guards are on for Portuguese (Brazil) and their word lists; what each guard does is code in the app. The scores under *How it was measured* are with the guards.- **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.- **A card for each change** that names the error ("Subject–verb agreement") and, on request, explains it.
`quickstart.py` and the in-browser demo run the model on its own, without the guards.
## Licence and attribution
The model weights and the files in this repository are released under the[Apache License 2.0](LICENSE). If you redistribute the model or a model built from it, keep the[NOTICE](NOTICE) file with it (Apache-2.0, section 4(d)).
The training data carries its own terms. Wikipedia text is © Wikipedia contributors,[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/). Tatoeba sentences are from[tatoeba.org](https://tatoeba.org), [CC BY 2.0 FR](https://creativecommons.org/licenses/by/2.0/fr/). The baseencoder is BERTimbau, `neuralmind/bert-base-portuguese-cased`, by Fábio Souza, Rodrigo Nogueira and Roberto Lotufo(NeuralMind), MIT licence: *BERTimbau: Pretrained BERT Models for Brazilian Portuguese*, BRACIS 2020. The taggingscheme follows GECToR (Omelianchuk et al., 2020, *GECToR – Grammatical Error Correction: Tag, Not Rewrite*); thePortuguese verb-form table was built for this model.
## How to cite
If you use or build on this model, please cite it:
```bibtex@misc{hartnett2026gectorptbr, author = {Hartnett, Patrick Andrew}, title = {Proofbird GECToR grammar model (Portuguese, Brazil)}, year = {2026}, publisher = {Hugging Face}, howpublished = {\url{https://huggingface.co/proofbird/gector-bert-pt-br}}, note = {Proofbird, https://proofbird.app}}```
If you build on this model, a link back to this page is appreciated.
## Contact
Published by Patrick Andrew Hartnett as personal work. Questions and reports: open a discussion on this repository.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159{
"guards": [
{
"type": "velar_orthography",
"note": "built-in (always on): reject a spurious h-insertion on a non-velar stem"
},
{
"type": "elision_echo",
"note": "built-in (always on): collapse a redundant elision echo (un'ora ora -> un'ora)"
},
{
"type": "auxiliary_number",
"note": "built-in (always on): keep 'e`' before a singular participle ('E` andata' is 3sg and correct; 'sono' would flip it to 1sg)"
},
{
"type": "suppress_append_words",
"words": "o|a|os|as|um|uma|de|em|que|e|se|do|da|no|na|ao|à",
"note": "drop a stray appended article/preposition (the retired drop_word artifact)"
},
{
"type": "agreement_needs_anchor",
"suffixes": "o|a|os|as|e|es|s|m|am|em|mos|amos|emos|imos",
"pairs": "são>é|é>são|estão>está|está>estão|têm>tem|tem>têm|vão>vai|vai>vão|fazem>faz|faz>fazem|eram>era|era>eram|estavam>estava|estava>estavam|foram>foi|foi>foram|dizem>diz|diz>dizem|podem>pode|pode>podem|querem>quer|quer>querem|sabem>sabe|sabe>sabem|dão>dá|dá>dão|vêm>vem|vem>vêm|tinham>tinha|tinha>tinham|somos>são|são>somos|estamos>estão|estão>estamos|temos>têm|têm>temos|vamos>vão|vão>vamos",
"words": "o|a|os|as|um|uma|uns|umas|do|da|dos|das|no|na|nos|nas|ao|à|aos|às|pelo|pela|pelos|pelas|meu|minha|meus|minhas|teu|tua|teus|tuas|seu|sua|seus|suas|nosso|nossa|nossos|nossas|este|esta|estes|estas|esse|essa|esses|essas|aquele|aquela|aqueles|aquelas|cada|outro|outra|outros|outras|algum|alguma|alguns|algumas|nenhum|nenhuma|vários|várias|muitos|muitas|poucos|poucas|todos|todas|ambos|ambas|dois|duas|três|quatro|cinco|eu|tu|ele|ela|você|nós|eles|elas|vocês",
"note": "pro-drop (the IT/ES lesson, before the first PT train): an agreement-shaped edit or a listed verb pair needs a determiner or subject pronoun in view; an article-shaped word before a verb form is a clitic (Eu a vi), not an anchor",
"personClitics": "me|te|nos|vos"
},
{
"type": "epicene_article",
"words": "estudante|artista|colega|jovem|cliente|paciente|agente|dentista|jornalista|turista|atleta|cantante|presidente|gerente|intérprete|pianista|motorista|taxista|recepcionista|rececionista|economista|especialista|terapeuta|psiquiatra|pediatra|astronauta|detetive|representante|assistente|docente|cônjuge|cônjuges|líder|mártir|policial|polícia|guia|modelo|testemunha|criança|pessoa|vítima|personagem|indígena|adolescente|imigrante|emigrante|residente|participante|concorrente|estagiário|melhor|pior|maior|menor|caixa|laranja|rosa|vinho|creme|violeta|lilás|cereja|groselha",
"pairs": "o>a|a>o|um>uma|uma>um|os>as|as>os",
"note": "o/a estudante, o/a artista, o/a colega: both genders are correct - an article gender swap is never a fix"
},
{
"type": "verb_person_needs_subject",
"pairs": "eu>1S|tu>2S|ele>3S|ela>3S|você>3S|nós>1P|eles>3P|elas>3P|vocês>3P",
"words": "o|a|os|as|um|uma|uns|umas|do|da|dos|das|no|na|nos|nas|ao|à|aos|às|pelo|pela|pelos|pelas|meu|minha|meus|minhas|teu|tua|teus|tuas|seu|sua|seus|suas|nosso|nossa|nossos|nossas|este|esta|estes|estas|esse|essa|esses|essas|aquele|aquela|aqueles|aquelas|cada|outro|outra|outros|outras|algum|alguma|alguns|algumas|nenhum|nenhuma|vários|várias|muitos|muitas|poucos|poucas|todos|todas|ambos|ambas|dois|duas|três|quatro|cinco",
"note": "pro-drop: with no subject in view the verb's person is the writer's choice (moramos -> *moro)"
},
{
"type": "keep_bare_plural",
"words": "de|só|sem|com",
"note": "a plural noun with no determiner after de/só/sem/com is a legit bare plural (cheio de livros -> *livro)"
},
{
"type": "suffix_redirect",
"from": "es",
"to": "s",
"suffixes": "a|e|o",
"note": "+es on a word ending in an unstressed vowel is +s: interessante -> interessantes, never *interessantees"
},
{
"type": "verb_form_accent",
"note": "never add an accent to a token that is itself a present-tense verb form (the biography-preterite lie)",
"allow": "têm|vêm|contêm|detêm|entretêm|mantêm|obtêm|retêm|sustêm|convêm|intervêm|provêm"
},
{
"type": "keep_repeated_names",
"note": "a repeated CAPITALISED word is a name, never a doubled word to delete (2026-10-17, from the EN judge pass)"
},
{
"type": "no_unknown_replacement",
"scope": "strict",
"note": "never propose a non-word (word knowledge; strict: a misspelling re-inflected into another non-word is held too; runs last)"
},
{
"type": "redirect_replace",
"from": "por",
"to": "pelo",
"redirect": "pôr",
"whenPrevIs": "vou|vai|vais|vamos|vão|ia|iam|íamos|quero|quer|queres|queremos|querem|queria|queriam|posso|pode|podes|podemos|podem|podia|podiam|preciso|precisa|precisas|precisamos|precisam|devo|deve|deves|devemos|devem|devia|deviam|para",
"note": "'por o' after a verb that takes an infinitive (vou, quero, posso, preciso, deve …) or 'para' is the verb pôr, not the contraction pelo (pt-BR run 1 gold 2026-11-13: Vou por o livro na mesa -> *pelo)"
},
{
"type": "redirect_replace",
"from": "por",
"to": "pela",
"redirect": "pôr",
"whenPrevIs": "vou|vai|vais|vamos|vão|ia|iam|íamos|quero|quer|queres|queremos|querem|queria|queriam|posso|pode|podes|podemos|podem|podia|podiam|preciso|precisa|precisas|precisamos|precisam|devo|deve|deves|devemos|devem|devia|deviam|para",
"note": "'por o' after a verb that takes an infinitive (vou, quero, posso, preciso, deve …) or 'para' is the verb pôr, not the contraction pelo (pt-BR run 1 gold 2026-11-13: Vou por o livro na mesa -> *pelo)"
},
{
"type": "redirect_replace",
"from": "por",
"to": "pelos",
"redirect": "pôr",
"whenPrevIs": "vou|vai|vais|vamos|vão|ia|iam|íamos|quero|quer|queres|queremos|querem|queria|queriam|posso|pode|podes|podemos|podem|podia|podiam|preciso|precisa|precisas|precisamos|precisam|devo|deve|deves|devemos|devem|devia|deviam|para",
"note": "'por o' after a verb that takes an infinitive (vou, quero, posso, preciso, deve …) or 'para' is the verb pôr, not the contraction pelo (pt-BR run 1 gold 2026-11-13: Vou por o livro na mesa -> *pelo)"
},
{
"type": "redirect_replace",
"from": "por",
"to": "pelas",
"redirect": "pôr",
"whenPrevIs": "vou|vai|vais|vamos|vão|ia|iam|íamos|quero|quer|queres|queremos|querem|queria|queriam|posso|pode|podes|podemos|podem|podia|podiam|preciso|precisa|precisas|precisamos|precisam|devo|deve|deves|devemos|devem|devia|deviam|para",
"note": "'por o' after a verb that takes an infinitive (vou, quero, posso, preciso, deve …) or 'para' is the verb pôr, not the contraction pelo (pt-BR run 1 gold 2026-11-13: Vou por o livro na mesa -> *pelo)"
},
{
"type": "block_replace",
"from": "é",
"to": "e",
"note": "é -> e removes the verb: 'A guerra é o inferno', 'Três vezes quatro é doze', 'não é permitido, é?' (2026-11-13 pt-BR run 1 Tatoeba). Writing é for the conjunction e is rare; a coordination read as a copula is a lie the model learned."
},
{
"type": "block_replace",
"from": "É",
"to": "E",
"note": "the capitalised form of the é -> e block"
},
{
"type": "redirect_replace",
"from": "E",
"to": "É",
"redirect": "E",
"whenNextIs": "que|o|a|os|as|se|depois|então|agora|também|assim|não|eu|ele|ela|você|nós|eles|elas|vocês|quando|por|com|um|uma|isso|aí|daí|já|ainda|mesmo",
"note": "a sentence opening with the conjunction 'E que tal …', 'E o que a gente …' is correct (2026-11-13 pt-BR run 1 Tatoeba)"
},
{
"type": "redirect_replace",
"from": "está",
"to": "esta",
"redirect": "está",
"whenNextIs": "tarde|cedo|bem|mal|frio|calor|quente|escuro|claro|certo|errado|pronto|pronta|ótimo|ótima|bom|boa|difícil|fácil|tudo|aqui|ali|lá|longe|perto|cheio|cheia|vazio|vazia|chovendo|nevando|ventando|tranquilo|tranquila|ocupado|ocupada|livre|caro|cara|barato|barata|feito|feita|melhor|pior|muito|tão|mais|menos|sempre|nunca",
"note": "'Está tarde' (it is late) is a sentence; 'Esta tarde' (this afternoon) is too - before an adverb/adjective the verb stays (2026-11-13 pt-BR run 1 Tatoeba)"
},
{
"type": "redirect_replace",
"from": "à",
"to": "a",
"redirect": "à",
"whenNextEndsWith": "a|ã|ade|ção|são|gem|ez|ice|ura|ulher|ave|oite|arde|arte|ãe|ente|ome|orte|ie",
"note": "the crase before a feminine noun is right: 'segreda à mulher', 'trancou à chave', 'suba à cabeça' (2026-11-13 pt-BR run 1 Tatoeba); the real overuse (à + infinitive, à ele, à pé) still gets fixed"
},
{
"type": "block_replace",
"from": "deles",
"to": "dele",
"note": "possessive number follows the owner, which the sentence may not show: 'o gato deles' (2026-11-13 pt-BR run 1 Tatoeba)"
},
{
"type": "block_replace",
"from": "delas",
"to": "dela",
"note": "possessive number follows the owner, which the sentence may not show: 'o gato deles' (2026-11-13 pt-BR run 1 Tatoeba)"
},
{
"type": "block_replace",
"from": "dele",
"to": "deles",
"note": "possessive number follows the owner, which the sentence may not show: 'o gato deles' (2026-11-13 pt-BR run 1 Tatoeba)"
},
{
"type": "block_replace",
"from": "dela",
"to": "delas",
"note": "possessive number follows the owner, which the sentence may not show: 'o gato deles' (2026-11-13 pt-BR run 1 Tatoeba)"
}
]
}1234567891011121314151617181920212223242526272829303132333435363738394041{
"base": "neuralmind/bert-base-portuguese-cased",
"encoder": "neuralmind/bert-base-portuguese-cased",
"precision": "fp32",
"tokenizer": "wordpiece",
"logits_labels_dim": 5000,
"logits_d_dim": 2,
"onnx_inputs": [
"input_ids",
"attention_mask"
],
"onnx_outputs": [
"logits_labels",
"logits_d"
],
"defaults": {
"keep_confidence": 0.0,
"min_error_prob": 0.0,
"n_iteration": 5
},
"run_id": "2026-11-13-1728",
"exported_at": "2026-11-13T21:59:58+00:00",
"checkpoint": "ckpt_best.pt",
"git_commit": null,
"recipe_sha256": {
"build_dataset.py": "60d98041be3f",
"preprocess.py": "384e6c617e5e",
"train.py": "c6a3c61a7b2d",
"export_onnx.py": "89ea01132729",
"runrecord.py": "eedd5c637a60",
"tatoeba_split.py": "7cf3f8b22747",
"selection.py": "b20862d4cb42",
"lanes.py": "2fed6c3e606d",
"corrupt_pt.py": "29c0df88c9f3",
"morph_pt.py": "c23ffc0f4ee9",
"language-rules.pt.json": "6a6d010e10c8",
"variant_pt.py": "2cdd5ea9aad5",
"accent_confusables_pt.json": "48c61f506f45"
},
"version": "1.0.0"
}1234567{ "version": 1, "language": "pt", "_comment": "Per-bundle language facts (see C# LanguageRules / ADR-004). stripTrailingTerminator true: the PT 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). 'além' is the single-token head of 'além disso'; multi-word connectors (no entanto, por isso) can't be matched by the single-word splitter and are deliberately absent. Validate against lang/pt/gold comma_context at eval (gold suite pending — created ahead of the PT model so the bundle export picks it up).", "stripTrailingTerminator": true, "clauseConjunctions": ["mas", "e", "ou", "porém", "pois", "porque", "então", "portanto", "contudo", "todavia", "entretanto", "senão", "logo", "depois", "além", "enquanto", "embora"]}123version https://git-lfs.github.com/spec/v1oid sha256:67355bac5f6117ba9402228670966019852a41b4533e0bd177225766a65c42a4size 448996260123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Proofbird grammar model (Portuguese (Brazil)): quick start\n", "\n", "Run [`proofbird/gector-bert-pt-br`](https://huggingface.co/proofbird/gector-bert-pt-br) in a few lines. It is small (about 450 MB), runs on a CPU in about\n", "30 ms a sentence, and needs no API key." ] }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "!pip install -q onnxruntime tokenizers huggingface_hub" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. Load the model and correct a sentence\n", "\n", "`quickstart.py`, published with the model, downloads it, runs it, and returns the corrected text plus one suggestion per\n", "change (character position, original, replacement)." ] }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "import importlib.util\n", "from huggingface_hub import hf_hub_download\n", "\n", "path = hf_hub_download(\"proofbird/gector-bert-pt-br\", \"quickstart.py\")\n", "spec = importlib.util.spec_from_file_location(\"quickstart\", path)\n", "quickstart = importlib.util.module_from_spec(spec)\n", "spec.loader.exec_module(quickstart)\n", "\n", "model = quickstart.Gector(\"proofbird/gector-bert-pt-br\")\n", "corrected, suggestions = model.correct(\"A casa são muito bonito.\")\n", "print(corrected)\n", "suggestions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. See every pass\n", "\n", "The model does not write text. For every word it picks one of 5 000 edits; the corrected sentence goes back in until\n", "nothing changes, so connected errors are fixed one after the other. `verbose=True` prints what each pass sent and got\n", "back." ] }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "corrected, suggestions = model.correct(\"A casa são muito bonito.\", verbose=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. Your own text\n", "\n", "`model.passes` holds the same per-pass detail as a list of dictionaries, if you want to build on it." ] }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "text = \"As crianças brinca no jardim.\"\n", "print(model.correct(text)[0])\n", "model.passes[0][\"words\"]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "Published by Patrick Andrew Hartnett. The [Proofbird](https://proofbird.app) writing assistant for Windows uses this\n", "model on-device and adds the guards in `gector-guards.json` and an explanation for each change. If you build on this\n", "model, a link back is appreciated." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python" }, "colab": { "provenance": [] } }, "nbformat": 4, "nbformat_minor": 5}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236"""Proofbird GECToR grammar model (Portuguese (Brazil)): a complete, minimal way to run it (Python).
pip install onnxruntime tokenizers huggingface_hub numpy python quickstart.py "A casa são muito bonito."
This is the same algorithm the Proofbird app runs (C#), minus the guards in gector-guards.json (see the model card,"What Proofbird adds"). Published by Patrick Andrew Hartnett - https://proofbird.app"""import argparseimport difflibimport jsonimport osimport re
import numpy as npimport onnxruntime as ortfrom huggingface_hub import snapshot_downloadfrom tokenizers import Tokenizer
MODEL = "proofbird/gector-bert-pt-br"WORD = re.compile(r"\w+(?:'\w+)?|[^\w\s]") # a word (with one apostrophe inside), or one punctuation mark
class Gector: def __init__(self, model=MODEL, keep_confidence=0.0, min_error_prob=0.0): """keep_confidence: a bonus added to "$KEEP" before choosing (higher = fewer, safer edits). min_error_prob: ignore an edit, or a whole sentence, the model is less sure of than this. Both 0 by default, as in the Proofbird app.""" self.keep_confidence, self.min_error_prob = keep_confidence, min_error_prob path = model if os.path.isdir(model) else snapshot_download(model) cfg = json.load(open(os.path.join(path, "config.json"), encoding="utf-8")) self.labels = [cfg["id2label"][str(i)] for i in range(len(cfg["id2label"]))] self.keep = self.labels.index(cfg.get("keep_label", "$KEEP")) self.incorrect = {v: int(k) for k, v in cfg["d_id2label"].items()}[cfg.get("incorrect_label", "$INCORRECT")] rules_path = os.path.join(path, "language-rules.json") rules = json.load(open(rules_path, encoding="utf-8")) if os.path.exists(rules_path) else {} # The final full stop comes off before the model and goes back on after (where the bundle says so). self.strip = rules.get("stripTerminators", ".!?") if rules.get("stripTrailingTerminator") else "" # Articles written glued to the next word with an apostrophe, which the model reads as two words (bundle data). self.glued = set((rules.get("elision") or {}).get("nonElidingArticles") or rules.get("nonElidingArticles") or []) self.verbs = {} # "<word>_<from>_<to>" -> the verb form, for $TRANSFORM_VERB_* verb_path = os.path.join(path, "verb-form-vocab.txt") if os.path.exists(verb_path): for line in open(verb_path, encoding="utf-8"): if ":" in line: words, tags = line.strip().split(":") w1, w2 = words.split("_") self.verbs[f"{w1}_{tags}"] = w2 self.tokenizer = Tokenizer.from_file(os.path.join(path, "tokenizer.json")) self.session = ort.InferenceSession(os.path.join(path, "model.onnx"), providers=["CPUExecutionProvider"])
# --- one pass: words in, one tag per word out ------------------------------------------------------------- def tag(self, words): enc = self.tokenizer.encode(words, is_pretokenized=True) # [CLS] w1 ... wn [SEP]; [CLS] stands for $START input_ids = np.array([enc.ids], dtype=np.int64) logits_labels, logits_d = self.session.run( ["logits_labels", "logits_d"], {"input_ids": input_ids, "attention_mask": np.ones_like(input_ids)}) probs = softmax(logits_labels[0]) # [tokens, 5000] probs[:, self.keep] += self.keep_confidence wrong = softmax(logits_d[0])[:, self.incorrect] # [tokens] result, seen = [], set() for t, w in enumerate(enc.word_ids): # one label per word, read at its first token word = 0 if t == 0 else (None if w is None else w + 1) if word is None or word in seen: continue seen.add(word) best = int(probs[t].argmax()) label = self.labels[best] if probs[t, best] >= self.min_error_prob else "$KEEP" result.append((label, float(probs[t, best]), float(wrong[t]))) if max(r[2] for r in result) < self.min_error_prob: # no word is confidently wrong: keep the sentence result = [("$KEEP", p, e) for _, p, e in result] return input_ids, logits_labels.shape, result
# --- apply one tag to one word ------------------------------------------------------------------------------ def edit(self, word, label): if label.startswith("$APPEND_"): return word + " " + label[8:] if word == "$START" or label == "$KEEP": return word if label.startswith("$REPLACE_"): return label[9:] if label == "$DELETE": return "" if label.startswith("$TRANSFORM_SUF_"): # change the ending: $TRANSFORM_SUF_<old>_<new> old, new = label[15:].split("_", 1) if not word.endswith(old): return word stem = word[: len(word) - len(old)] return stem + new if label.startswith("$TRANSFORM_VERB_"): # verb form from verb-form-vocab.txt return self.verbs.get(f"{word}_{label[16:]}", word) if label == "$TRANSFORM_CASE_CAPITAL": return word[:1].upper() + word[1:].lower() if label == "$TRANSFORM_CASE_LOWER": return word.lower() if label == "$TRANSFORM_CASE_UPPER": return word.upper() if label == "$TRANSFORM_AGREEMENT_PLURAL": return word + "s" if label == "$TRANSFORM_AGREEMENT_SINGULAR": return word[:-1] if label == "$TRANSFORM_SPLIT_HYPHEN": return word.replace("-", " ") if label.startswith("$MERGE_"): return word + " " + label return word
# --- the whole call: up to 5 passes, then the suggestions ------------------------------------------------- def correct(self, text, max_passes=5, verbose=False): core, tail = text, "" if self.strip and text.rstrip()[-1:] and text.rstrip()[-1] in self.strip: core, tail = text.rstrip()[:-1], text[len(text.rstrip()) - 1:] plain = core.replace("’", "'") # the models were trained on straight apostrophes words = self.words(plain) self.passes = [] # what each pass saw and did (for printing or a UI) for n in range(1, max_passes + 1): input_ids, shape, tags = self.tag(words) edited = [self.edit(w, label) for w, (label, _, _) in zip(["$START"] + words, tags)] tokens = (" ".join(e for e in edited if e).replace(" $MERGE_HYPHEN ", "-") .replace(" $MERGE_SPACE ", "").split()) new_words = [x for t in rejoin(t for t in tokens if t != "$START") for x in self.words(t)] self.passes.append({ "pass": n, "input": join(" ".join(words)), "input_ids": input_ids[0].tolist(), "logits_labels_shape": list(shape), "words": [{"word": w, "tag": label, "probability": round(p, 6), "wrong": round(wrong, 6), "edit": e if e != w else None} for w, (label, p, wrong), e in zip(["$START"] + words, tags, edited)], "result": join(" ".join(new_words)), "changed": new_words != words}) if verbose: print_pass(self.passes[-1]) if new_words == words: break words = new_words found = self.suggestions(plain, words) # same length as core, so positions match the real text corrected = core for f in reversed(found): # apply right to left, so positions stay valid f["original"] = core[f["start"]: f["start"] + f["length"]] corrected = corrected[: f["start"]] + f["replacement"] + corrected[f["start"] + f["length"]:] return corrected + tail, found
def words(self, text): return [w for w, _, _ in self.spans(text)]
def spans(self, text, surface=False): """The words of the text with their character positions. An article glued to the next word with an apostrophe (the bundle's list) is split into the two words the model was trained on.""" out = [] for m in WORD.finditer(text): article, sep, rest = m.group().partition("'") if sep and rest and article.lower() in self.glued: # the article keeps its apostrophe for comparing (so splitting it counts as a change), not for the model first = article + "'" if surface else article out += [(first, m.start(), m.start() + len(first)), (rest, m.end() - len(rest), m.end())] else: out.append((m.group(), m.start(), m.end())) return out
def suggestions(self, original, corrected_words): """Compare the original words with the corrected ones: one suggestion per changed stretch, with its character position in the ORIGINAL text. Unchanged text keeps the writer's own spacing and characters.""" spans = self.spans(original, surface=True) a = [w for w, _, _ in spans] out = [] for op, i1, i2, j1, j2 in difflib.SequenceMatcher(a=a, b=corrected_words, autojunk=False).get_opcodes(): if op == "equal": continue new = join(" ".join(corrected_words[j1:j2])) if i1 == i2: # pure insertion if i1 < len(a): # before a word: "new "; before punctuation: " new" start = end = spans[i1][1] if new[-1:] in OPENING: pass # an opening mark hugs the next word elif i1 == 0 or a[i1][0].isalnum(): new = new + " " else: new = " " + new else: # at the very end start = end = spans[-1][2] if spans else 0 new = (" " if new[:1].isalnum() else "") + new else: start, end = spans[i1][1], spans[i2 - 1][2] if new and end < len(original) and original[end].isalnum() and new[-1].isalnum(): new += " " # a glued article split off: keep a space before the next word if not new: # pure deletion: take one neighbouring space with it if end < len(original) and original[end] == " ": end += 1 elif start > 0 and original[start - 1] == " ": start -= 1 out.append({"start": start, "length": end - start, "original": original[start:end], "replacement": new}) return out
OPENING = "([{“«\"" # marks that hug the word after themCLOSING = ".,;:!?)]}%»”" # marks that hug the word before them
def softmax(x): e = np.exp(x - x.max(axis=-1, keepdims=True)) return e / e.sum(axis=-1, keepdims=True)
def print_pass(p): print(f"\n--- pass {p['pass']}: \"{p['input']}\"") print(f"request input_ids {p['input_ids']} attention_mask all 1") print(f"response logits_labels {p['logits_labels_shape']} logits_d {p['logits_labels_shape'][:2] + [2]}") for w in p["words"]: print(f" {w['word']:<12} wrong {w['wrong']:6.1%} {w['tag']} {w['probability']:.1%}") print(f"result \"{p['result']}\"" + ("" if p["changed"] else " (no change: stop)"))
def rejoin(tokens): """A word the model ends with an apostrophe hugs the next word.""" out = [] for t in tokens: if out and len(out[-1]) > 1 and out[-1].endswith("'") and t[:1].isalnum(): out[-1] += t else: out.append(t) return out
def join(text): """Words back to normal text: no space before closing punctuation or after an opening mark.""" text = re.sub(f" ([{re.escape(CLOSING)}])", r"\1", " ".join(text.split())) return re.sub(f"([{re.escape(OPENING.replace(chr(34), ''))}]) ", r"\1", text)
if __name__ == "__main__": ap = argparse.ArgumentParser() ap.add_argument("text") ap.add_argument("--model", default=MODEL, help="a Hugging Face repo id or a local folder") args = ap.parse_args() corrected, found = Gector(args.model).correct(args.text, verbose=True) print(f"\ncorrected: \"{corrected}\"") print("suggestions:", json.dumps(found, indent=2, ensure_ascii=False))123456789101112131415{ "backend": "tokenizers", "cls_token": "[CLS]", "do_lower_case": false, "is_local": false, "local_files_only": false, "mask_token": "[MASK]", "model_max_length": 1000000000000000019884624838656, "pad_token": "[PAD]", "sep_token": "[SEP]", "strip_accents": null, "tokenize_chinese_chars": true, "tokenizer_class": "BertTokenizer", "unk_token": "[UNK]"}LICENSEAdded+202
NOTICEAdded+9
README.mdAdded+247
config.jsonAdded
gector-guards.jsonAdded+159
gector-meta.jsonAdded+41
language-rules.jsonAdded+7
model.onnxAdded+3
quickstart.ipynbAdded+118
quickstart.pyAdded+236
tokenizer.jsonAdded
tokenizer_config.jsonAdded+15
verb-form-vocab.txtAdded
vocab.txtAdded