Skip to main content

langtool

Grammar, style and typography checking for more than 30 languages, based on the rules of LanguageTool based off commit bc7e597. This is a port of the LanguageTool core (written in Java) to Python, with a C extension for the performance critical parts. No Java and no server are needed.

import langtool

tool = langtool.LanguageTool('en-US')
for m in tool.check('This are a test. He go to school.'):
    print(m.offset, m.length, m.rule_id, m.message, m.replacements)

print(tool.correct('This are a test.'))  # These are a test.

Installation

pip install lang-tool

The package is distributed as source; a C compiler is needed to build the optional C extension (langtool._speedups). Without it a pure Python implementation is used, which is about two times slower.

Building the extension also compiles the grammar and disambiguation rules of all languages into static table files that are installed with the package (langtool/_rule_tables/<code>.ltrt, about 150 MB; see below). This needs lxml and regex at build time (they are build requirements) and about 20 seconds on 16 cores (about 3 minutes of CPU time; the languages are processed in parallel, LANGTOOL_RULE_TABLES_JOBS sets the number of processes). python setup.py build_ext --inplace writes the table files into the source tree. LANGTOOL_NO_RULE_TABLES=1 builds the extension without them.

Static rule tables

The rules of the built-in languages (all rule files of all variants: grammar, style, the rules for speakers of other mother tongues and the disambiguation rules) are compiled at build time into read-only table files, one per language (tools/gen_rule_tables.py loads them with the XML loader of the package, so they are the same by construction). The C extension memory-maps the file of a language when it is first used and selects and matches the rules on the tables in place, and applies the disambiguation rules and the anti-patterns there; the Python objects of a rule are only created when they are needed (when the rule matched, or when code asks for the rules, e.g. JLanguageTool.get_all_rules()), and they are the same objects as those the XML loader creates. Loading the rules takes no time, there is no slow first start for them, and processes share the pages of the tables (e.g. forked servers). A table file is only used if it is the one of the build of the extension (format, size and a build id are checked); LANGTOOL_RULE_TABLES_DIR is another directory with the table files (of the same build).

The tables are not used (the rules are loaded from the XML files and the disk cache as before) in the pure Python mode, for languages added with langtool.languages.register_language(), with a custom filter factory and when the table file is missing, damaged or of another build, or when they are stale: when a rule file, an entity file, a message bundle or a module of the XML loading changed after the extension was built (an installed package is checked with the hashes of its manifest, a source tree with the size and modification time of the files). Stale tables are logged on the langtool.static logger and shown by langtool.static_rules_status(); rebuild the extension to update them. LANGTOOL_STATIC_RULES=0 disables the tables. Rules added at runtime (add_rule(), rule files of the user) work together with the static rules.

Dictionaries

Most languages need binary part-of-speech dictionaries (morfologik format). They are too large to be bundled and are downloaded from Maven Central the first time a language is used (checksums are verified), and cached in the user cache directory (~/.cache/langtool on Linux). The same mechanism provides the word lists of the spell checkers, for English the OpenNLP models of the chunker and, for Japanese, the IPADIC dictionary of the morphological analyzer. To download them ahead of time:

python -m langtool download en de fr
python -m langtool download --spelling en-US de-DE   # also the Hunspell dictionaries

The cache directory is used for all downloads (also the Hunspell dictionaries for spell checking). It can be set with the cache_dir argument of LanguageTool, with langtool.set_cache_dir(path) (both are process-wide settings), with --cache-dir on the command line or with the LANGTOOL_CACHE_DIR environment variable (used if nothing else is set):

tool = langtool.LanguageTool('de-DE', cache_dir='/srv/langtool-cache')

To use already downloaded dictionaries (for example the jars of a LanguageTool installation, or a directory with the .dict and .info files), pass dictionary_path or set LANGTOOL_DICT_PATH:

tool = langtool.LanguageTool('de-DE', dictionary_path='/opt/LanguageTool-6.6', download=False)

Disk cache

Loading a language means parsing thousands of XML rules, compiling their regular expressions and building word lists and other tables from the data files, which takes a few seconds for the large languages. The results are cached on disk the first time, after which creating a LanguageTool and the first checks are several times faster (e.g. German: about 1 second instead of 5 to 6 seconds until the first result). The results of the checks are the same with and without the cache.

The cache is in the derived directory of the cache directory (see above, e.g. ~/.cache/langtool/derived), or in the directory given by the LANGTOOL_DISK_CACHE_DIR environment variable. It takes up to about 20 MB per language (English, German), less than 1 MB for most languages, about 90 MB for all of them. Entries are invalidated automatically when the package (its version, code or data files), the Python version, the use of the C extension or the downloaded dictionaries they were built from change. For an installed package, a manifest written when the package is built (a hash of all its files) stands for the code and data files, which do not change after the installation; in a source tree (or with LANGTOOL_DISK_CACHE_VERIFY=1) the size and modification time of every file are looked at. Entries are written atomically, so concurrent processes can share the cache, and an unreadable or corrupt entry is silently rebuilt. The directory must not be writable by other users (the entries are Python pickles). The rules of languages added with langtool.languages.register_language() are not cached (changing the built-in language definitions in place requires disabling the cache).

The rules of the built-in languages normally come from the static rule tables (see above) and are not cached; when the tables are not used the rules are cached per rule file, so the variants of a language (e.g. en-US, en-GB, en-AU) share the entries of the common files and loading a further variant takes about a second even the first time.

The cache directory is kept below 512 MB: when it grows beyond that, the least recently used entries (of all package versions) are removed. The limit can be set with LANGTOOL_DISK_CACHE_MAX_MB (0 for no limit) or the max_size argument of set_disk_cache().

To disable the cache set LANGTOOL_DISK_CACHE=0 (or use --no-disk-cache on the command line), or call:

langtool.set_disk_cache(False)                         # process-wide
langtool.set_disk_cache(True, directory='/srv/lt-derived')   # another directory
langtool.set_disk_cache(True, max_size=200 << 20)      # at most 200 MB
langtool.clear_disk_cache()                            # remove all entries

Spell checking

Spell checking is optional and off by default. When it is on, misspelled words are reported as matches of the rule HUNSPELL_RULE (category TYPOS, issue type Misspelling) with suggestions:

tool = langtool.LanguageTool('en-US', spell_check=True)
for m in tool.check('This is an exmaple.'):
    print(m.rule_id, m.context, m.replacements)   # HUNSPELL_RULE exmaple ['example', ...]

tool.spell_check = False   # can be switched at any time

It uses Hunspell dictionaries (checked with langtool.hunspell, a port of Hunspell: in C in the extension, with an identical pure Python fallback). By default the dictionary of the language is downloaded from the LibreOffice dictionaries (a pinned commit, checksums verified; langtool.hunspell_dictionary_info(code) tells which one is used and python -m langtool spelling-languages lists them all). The dictionaries have their own licenses (see the repository). Your own dictionaries can be used instead, given as a mapping from language or variant codes to a path prefix (the .aff and .dic files) or an (aff, dic) pair of paths:

tool = langtool.LanguageTool('en-US', spell_check=True,
                             hunspell_dictionaries={'en-US': '/usr/share/hunspell/en_US'})
tool = langtool.LanguageTool('de-CH', spell_check=True,
                             hunspell_dictionaries={'de': ('/dicts/de.aff', '/dicts/de.dic')})

The variant code (de-CH) is looked up first, then the language code (de). The words are checked like LanguageTool's spelling rules do it (HunspellRule/SpellingCheckRule): URLs, e-mail addresses, words without letters and words of the ignore and spelling lists of the language (ignore.txt, spelling.txt, ..., also multi-word entries) are ignored, words of prohibit.txt are always errors. Words containing digits and all-uppercase words are ignored too (attributes ignore_words_with_digits and ignore_all_uppercase of tool.spelling_rule).

Without a LibreOffice dictionary (Asturian, Crimean Tatar, Irish, Japanese, Khmer, Malayalam, Tagalog and Chinese) spell checking raises langtool.SpellCheckUnavailable unless a dictionary is given. For New Zealand English the British dictionary and for Balearic Catalan the general Catalan dictionary are used.

The internal spelling lookups of LanguageTool's rules and filters ("is this word misspelled", suggestions in rule messages) are not affected: they use LanguageTool's own speller dictionaries, as in Java.

API

  • langtool.LanguageTool(language, dictionary_path=None, download=True, mother_tongue=None, picky=False, spell_check=False, hunspell_dictionaries=None, cache_dir=None)
    • check(text) — list of Match objects (offset, length, rule_id, full_rule_id, message, short_message, replacements, category, line, column, context, ...)
    • correct(text, java_compat=False, max_rounds=100) — the corrected text: the first suggestion of a match is applied and the text checked again, until no match with suggestions is left (in each round one match per sentence is applied, so alternative fixes of the same error are not combined). java_compat=True applies the first suggestion of every match in a single pass, like Java's Tools.correctText
    • sentences(text), analyze(text) — sentence splitting and the analysis (tokens, part-of-speech tags, lemmas)
    • rules(), disable_rule(id), enable_rule(id), disable_category(id), enable_category(id)
    • spell_check (property, can be set), spelling_rule, hunspell_dictionary
  • langtool.check(text, language, spell_check=False, hunspell_dictionaries=None)
  • langtool.languages() — the supported language codes
  • langtool.download_dictionaries(code, spelling=False)
  • langtool.set_cache_dir(path), langtool.get_cache_dir()
  • langtool.set_disk_cache(enabled=True, directory=None, max_size=None), langtool.get_disk_cache_dir(), langtool.clear_disk_cache() — the disk cache of derived data (see above)
  • langtool.spell_check_languages(), langtool.hunspell_dictionary_info(code)
  • langtool.static_rules_status() — whether the static rule tables are used (see above)

There is also a command line interface: python -m langtool check -l en-US file.txt (-s for spell checking, --hunspell-dict [CODE=]PATH for a dictionary, --cache-dir DIR, --no-disk-cache, --clear-disk-cache).

Status

The engine of LanguageTool (XML pattern rules, disambiguation rules, unification, tokenization, tagging, synthesis, the language independent rules and filters) is ported and the rule sets of all languages are included. Spell checking is based on Hunspell dictionaries (see above) instead of LanguageTool's language specific speller rules. Statistical (n-gram / neural network) rules and remote rules are not part of this package. Some rules of LanguageTool are implemented in Java code specific to a language; those that are not ported yet are skipped, LanguageTool.unsupported_components() lists them. The abstract rule classes those language rules are built on (simple replacement, compounds, word coherency, repetitions, style statistics, ...) are in langtool.rules.abstract_rules; language specific code registers its components with langtool.extensions.register().

Testing

pip install -e .[test]
pytest

The tests run in parallel, on all CPU cores, with pytest-xdist (configured in pyproject.toml: -n auto --dist loadgroup); pytest -n 0 runs them sequentially, -n 4 on 4 workers (each worker needs up to about 1.5 GB of memory).

The tests include ports of the unit tests of the LanguageTool core and of the language modules. They run with the C extension; the pure Python implementation (the fallback when the extension can not be built) is checked by tests/test_c_vs_python.py, which compares the results of both implementations, and by a smoke test subset: LANGTOOL_PURE_PYTHON=1 pytest -m pure_smoke. The check of the example sentences of the XML rules of all languages against a baseline of known failures (tests/data/rule_test_baseline.json) needs the dictionaries and takes a while, it runs with LANGTOOL_LANGUAGE_TESTS=1 pytest tests/test_language_rules.py. tools/run_rule_tests.py [-v] <lang> gives a per-language report.

License

LGPL 2.1 or later, like LanguageTool. The rule files are part of LanguageTool and are under the same license.

Metadata

Release files for kovidgoyal-langtool 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for kovidgoyal-langtool 1.0.0
File Size Uploaded Provenance Actions
kovidgoyal_langtool-1.0.0.tar.gz 18.1 MB Without provenance Details for kovidgoyal_langtool-1.0.0.tar.gz

Release files / kovidgoyal_langtool-1.0.0.tar.gz

Download URL kovidgoyal_langtool-1.0.0.tar.gz
Size 18.1 MB
Tags Source
SHA-256 checksum
How to use checksums
2fa574ac4b0e335e4d2daa3e8275c1890cf59dd1eb5a1874d40f7e34cabf7fd0
BLAKE2b-256 checksum
How to use checksums
9dde8d24356c29ff21a0edd1d1856e2b26331f7883b7db3c4201f289493ca0a2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.8

Security for kovidgoyal-langtool 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page