language_tool_python package (full API reference)¶
Available modules¶
The following modules make up the public interface of language_tool_python.
Core - language_tool_python.server¶
Contains LanguageTool, the main class for interacting
with a local LanguageTool server, and
LanguageToolPublicAPI, a subclass that targets the
hosted public API instead.
LanguageTool server management module.
- class language_tool_python.server.LanguageTool(language: str | None = None, mother_tongue: str | None = None, remote_server: str | None = None, new_spellings: list[str] | None = None, new_spellings_persist: bool = True, host: str | None = None, config: Mapping[str, ConfigValue] | None = None, language_tool_download_version: str = '6.8', proxies: dict[str, str] | None = None)[source]¶
Bases:
objectInteract with the LanguageTool server for text checking and correction.
- Parameters:
language (str | None) – The language to be used by the LanguageTool server. If None, it will try to detect the system language.
mother_tongue (str | None) – The mother tongue of the user.
remote_server (str | None) – URL of a remote LanguageTool server. If provided, the local server will not be started.
new_spellings (list[str] | None) – Custom spellings to be added to the LanguageTool server.
new_spellings_persist (bool) – Whether the new spellings should persist across sessions.
host (str | None) – The host address for the LanguageTool server. Defaults to ‘localhost’.
config (collections.abc.Mapping[str, ConfigValue] | None) – Configuration options for the local LanguageTool server.
language_tool_download_version (str) – The version of LanguageTool to download if needed.
proxies (dict[str, str] | None) – A dictionary of proxies to use for server requests (e.g., {‘http’: ‘http://proxy:port’, ‘https’: ‘https://proxy:port’}).
- Raises:
ValueError – If incompatible constructor parameters are combined or the language tag is unsupported.
TypeError – If a config value has an unsupported type.
PathError – If config paths are invalid, the local LanguageTool installation cannot be prepared, or custom spellings are requested without a local LanguageTool installation.
ModuleNotFoundError – If no Java installation is detected for a local server.
SystemError – If the detected Java version is incompatible with the requested LanguageTool version.
TimeoutError – If the LanguageTool download request times out.
ServerError – If the server does not become ready or returns an invalid response while initializing.
LanguageToolError – If the server cannot be queried while initializing.
- close() None[source]¶
Close the server and perform necessary cleanup operations.
This method performs the following actions: 1. Checks if the server is alive, not remote and terminates it if necessary. 2. If new spellings are not set to persist and there are new spellings, it unregisters the spellings and clears the list of new spellings.
- property language: LanguageTag¶
Get the language tag associated with the server.
- Returns:
The language tag.
- Return type:
- property mother_tongue: LanguageTag | None¶
Get the mother tongue language tag.
- Returns:
The mother tongue language tag if set, otherwise None.
- Return type:
LanguageTag | None
- Raises:
ValueError – If the mother tongue tag is unsupported.
LanguageToolError – If supported languages cannot be fetched from the server.
- property enabled_rules_only: bool¶
Get whether only enabled rules/categories should be used.
- Returns:
True if using only enabled rules, False otherwise.
- Return type:
- property picky: bool¶
Get whether picky mode is enabled.
- Returns:
True if picky mode is enabled, False otherwise.
- Return type:
Get the premium API username.
- Returns:
The premium API username if set, otherwise None.
- Return type:
str | None
Get the premium API key.
- Returns:
The premium API key if set, otherwise None.
- Return type:
str | None
- property config: LanguageToolConfig | None¶
Get the server configuration.
This property is read-only as the configuration is set during initialization and cannot be changed while the server is running.
- Returns:
The configuration object if set, otherwise None.
- Return type:
LanguageToolConfig | None
- property language_tool_download_version: str¶
Get the LanguageTool version to download.
This property is read-only as the version is determined during initialization and the server cannot be re-downloaded with a different version at runtime.
- Returns:
The LanguageTool version string.
- Return type:
- property url: str¶
Get the LanguageTool server URL.
This property is read-only as the URL is determined during initialization and cannot be changed while the server is running.
- Returns:
The server URL (e.g., ‘http://localhost:8081/v2/’).
- Return type:
- property is_remote: bool¶
Get whether using a remote LanguageTool server.
This property is read-only as the remote status is determined during initialization and cannot be changed while the server is running.
- Returns:
True if using a remote server, False if using a local server.
- Return type:
- property host: str¶
Get the local server host address.
This property is read-only as the host address is determined during initialization and cannot be changed while the server is running.
- Returns:
The host address (e.g., ‘127.0.0.1’).
- Return type:
- property port: int¶
Get the local server port number.
This property is read-only as the port number is determined during initialization and cannot be changed while the server is running.
- Returns:
The port number (e.g., 8081).
- Return type:
- check(text: str) list[Match][source]¶
Check the given text for language issues using the LanguageTool server.
- Parameters:
text (str) – The text to be checked for language issues.
- Returns:
A list of Match objects representing the issues found in the text.
- Return type:
- Raises:
ServerError – If no response is received from the LanguageTool server or if the response shape is invalid.
ValueError – If the configured mother tongue tag is unsupported.
RateLimitError – If the public LanguageTool API rate limit is exceeded.
LanguageToolError – If the server query fails.
- check_matching_regions(text: str, pattern: str, flags: int = 0) list[Match][source]¶
Check only the parts of the text that match a regex pattern.
The returned Match objects can be applied to the original text with
language_tool_python.utils.correct().- Parameters:
text – The full text.
pattern – Regular expression defining the regions to check
flags – Regex flags (re.IGNORECASE, re.MULTILINE, etc.)
- Returns:
A list of Match objects with offsets adjusted to the original text.
- Return type:
- Raises:
ValueError – If the configured mother tongue tag is unsupported.
RateLimitError – If the public LanguageTool API rate limit is exceeded.
LanguageToolError – If the server query fails.
- correct(text: str) str[source]¶
Corrects the given text by applying language tool suggestions.
Applies only the first suggestion for each issue.
- Parameters:
text (str) – The text to be corrected.
- Returns:
The corrected text.
- Return type:
- Raises:
ValueError – If the configured mother tongue tag is unsupported.
RateLimitError – If the public LanguageTool API rate limit is exceeded.
LanguageToolError – If the server query fails.
- enable_spellchecking() None[source]¶
Enable spellchecking by removing spellcheck category exclusions.
This method updates the
disabled_categoriesattribute by removing any categories that are related to spell checking, which are defined in the_SPELL_CHECKING_CATEGORIESclass constant.
- class language_tool_python.server.LanguageToolPublicAPI(language: str | None = None, mother_tongue: str | None = None, new_spellings: list[str] | None = None, new_spellings_persist: bool = True, proxies: dict[str, str] | None = None)[source]¶
Bases:
LanguageToolA class to interact with the public LanguageTool API.
This class extends the
LanguageToolclass and initializes it with the remote server set to the public LanguageTool API endpoint.- Parameters:
language (str | None) – The language code to use for checking text (e.g., ‘en-US’).
mother_tongue (str | None) – The mother tongue language code, if specified (e.g., ‘en’).
new_spellings (list[str] | None) – A list of new spellings to register, if any.
new_spellings_persist (bool) – Whether to persist new spellings across sessions.
proxies (dict[str, str] | None) – A dictionary of proxies to use for requests to the remote server.
- Raises:
ValueError – If the language tag is unsupported.
PathError – If custom spellings are requested for the remote public API.
LanguageToolError – If the public API cannot be queried while initializing.
Match - language_tool_python.match¶
Contains the Match class that wraps a single language
issue returned by LanguageTool.
LanguageTool API Match object representation and utility module.
- class language_tool_python.match.Match(attrib: CheckMatch, text: str)[source]¶
Bases:
objectRepresent a language rule violation match.
- Parameters:
attrib (CheckMatch) – A raw LanguageTool API match. It is expected to contain
rule(withcategory,id, andissueType),context(withoffsetandtext),replacements(items withvalue),length, andmessage.text (str) – The original text in which the error occurred (the whole text, not just the context).
Example of a match object received from the LanguageTool API :
{ "message": "Possible spelling mistake found.", "shortMessage": "Spelling mistake", "replacements": [ {"value": "newt"}, {"value": "not"}, {"value": "new", "shortDescription": "having just been made"}, {"value": "news"}, {"value": "foot", "shortDescription": "singular"}, {"value": "root", "shortDescription": "underground organ of a plant"}, {"value": "boot"}, {"value": "noon"}, {"value": "loot", "shortDescription": "plunder"}, {"value": "moot"}, {"value": "Root"}, {"value": "soot", "shortDescription": "carbon black"}, {"value": "newts"}, {"value": "nook"}, {"value": "Lieut"}, {"value": "coot"}, {"value": "hoot"}, {"value": "toot"}, {"value": "snoot"}, {"value": "neut"}, {"value": "nowt"}, {"value": "Noor"}, {"value": "noob"}, ], "offset": 8, "length": 4, "context": {"text": "This is noot okay. ", "offset": 8, "length": 4}, "sentence": "This is noot okay.", "type": {"typeName": "Other"}, "rule": { "id": "MORFOLOGIK_RULE_EN_US", "description": "Possible spelling mistake", "issueType": "misspelling", "category": {"id": "TYPOS", "name": "Possible Typo"}, }, "ignoreForIncompleteSentence": False, "contextForSureMatch": 0, }
- FOUR_BYTES_POSITIONS: list[int] | None = None¶
The positions of 4-byte encoded characters in the text, registered by the previous match object (kept for optimization purposes if the text is the same).
- property matched_text: str¶
Return the substring from the context that corresponds to the matched text.
- Returns:
The matched text from the context.
- Return type:
- get_line_and_column(original_text: str) tuple[int, int][source]¶
Return the line and column number of the error in the context.
- Parameters:
original_text (str) – The original text in which the error occurred. We need this to calculate the line and column number, because the context has no more newline characters.
- Returns:
A tuple containing the line and column number of the error.
- Return type:
- Raises:
ValueError – If the original text does not contain the match context.
- select_replacement(index: int) None[source]¶
Keep only the replacement selected by the given index.
- Parameters:
index (int) – The index of the replacement to select.
- Raises:
ValueError – If there are no replacement suggestions.
ValueError – If the index is out of the valid range.
Utilities - language_tool_python.utils¶
Standalone helper functions:
correct() applies match suggestions to a text, and
classify_matches() categorises a list of matches as
CORRECT,
FAULTY, or
GARBAGE.
Utility functions for the LanguageTool library.
- class language_tool_python.utils.TextStatus(*values)[source]¶
Bases:
EnumStatus classification for matches.
- CORRECT = 'correct'¶
- FAULTY = 'faulty'¶
- GARBAGE = 'garbage'¶
- language_tool_python.utils.classify_matches(matches: list[Match]) TextStatus[source]¶
Classify matches as CORRECT, FAULTY, or GARBAGE.
This function checks the status of the matches and returns a corresponding
TextStatusvalue.- Parameters:
matches (list[Match]) – A list of Match objects to be classified.
- Returns:
The classification of the matches as a
TextStatusvalue.- Return type:
Exceptions - language_tool_python.exceptions¶
All custom exceptions raised by the library. Every exception inherits from
LanguageToolError, so a single
except LanguageToolError clause is sufficient to catch all library errors.
Exceptions used in the language_tool_python library.
- exception language_tool_python.exceptions.JavaError[source]¶
Bases:
LanguageToolErrorException raised for errors related to the Java backend of LanguageTool.
This exception is a subclass of
LanguageToolErrorand is used to indicate issues that occur when interacting with Java, such as Java not being found.
- exception language_tool_python.exceptions.LanguageToolError[source]¶
Bases:
ExceptionException raised for errors in the LanguageTool library.
This is a generic exception that can be used to indicate various types of errors encountered while using the LanguageTool library.
- exception language_tool_python.exceptions.PathError[source]¶
Bases:
LanguageToolErrorException raised for errors in the file path used in LanguageTool.
This error is raised when there is an issue with the file path provided to LanguageTool, such as the LanguageTool JAR file not being found, or a download path not being a valid available file path.
- exception language_tool_python.exceptions.RateLimitError[source]¶
Bases:
LanguageToolErrorException raised for errors related to rate limiting in the LanguageTool server.
This exception is a subclass of
LanguageToolErrorand is used to indicate issues such as exceeding the allowed number of requests to the public API without a key.
- exception language_tool_python.exceptions.ServerError[source]¶
Bases:
LanguageToolErrorRaised when interacting with the LanguageTool server fails.
This exception is a subclass of
LanguageToolErrorand is used to indicate issues such as server startup failures.
Server configuration - language_tool_python.config_file¶
LanguageToolConfig accepts a
ConfigValue dictionary and writes it to a
temporary file that is passed to the LanguageTool Java process via --config.
Module for configuring LanguageTool’s local server.
- language_tool_python.config_file.ConfigValue = os.PathLike[str] | language_tool_python._internals.utils.SupportsBool | str | int | float | collections.abc.Iterable[str]¶
Union of types accepted as values in the
LanguageToolConfigdictionary.os.PathLike[str],SupportsBool,str,int,float,collections.abc.Iterable[str]
- class language_tool_python.config_file.LanguageToolConfig(config: Mapping[str, PathLike[str] | SupportsBool | str | int | float | Iterable[str]])[source]¶
Bases:
objectConfiguration class for LanguageTool.
- Parameters:
config (collections.abc.Mapping[str, ConfigValue]) – Dictionary containing configuration keys and values.
Advanced¶
Download management - language_tool_python.download_lt¶
Handles downloading and caching the LanguageTool JAR. Exposed for advanced use cases
such as pinning a specific LanguageTool version or working with snapshot builds.
The default download version is given by LTP_DOWNLOAD_VERSION.
LanguageTool download module.
- language_tool_python.download_lt.LTP_DOWNLOAD_VERSION: str = '6.8'¶
Default LanguageTool version downloaded and used by the library.
- class language_tool_python.download_lt.LocalLanguageTool[source]¶
Bases:
ABCAbstract base class for managing local LanguageTool installations.
This class provides common functionality for handling LanguageTool downloads, installations, and server command generation. It supports both release versions and snapshot versions through its subclasses.
- classmethod from_version_name(version_name: str = '6.8') LocalLanguageTool[source]¶
Create a LocalLanguageTool instance from a version name.
This factory method determines the appropriate subclass (ReleaseLocalLanguageTool or SnapshotLocalLanguageTool) based on the version name format.
- Parameters:
version_name (str) – The version name (e.g., ‘6.8’, ‘20240101’, or ‘latest’).
- Returns:
An instance of the appropriate LocalLanguageTool subclass.
- Return type:
- Raises:
ValueError – If the version name format is not recognized.
- classmethod from_path(path: Path) LocalLanguageTool[source]¶
Create a LocalLanguageTool instance from a directory path.
This factory method extracts the version name from a LanguageTool directory path and creates the appropriate instance.
- Parameters:
path (pathlib.Path) – The path to a LanguageTool installation directory.
- Returns:
An instance of the appropriate LocalLanguageTool subclass.
- Return type:
- Raises:
ValueError – If the version cannot be determined from the path or the extracted version name is unsupported.
- abstractmethod download() None[source]¶
Download and install the LanguageTool version.
This abstract method must be implemented by subclasses to handle version- specific download logic.
- Raises:
NotImplementedError – Always, unless implemented by a subclass.
- classmethod get_installed_versions() list[LocalLanguageTool][source]¶
Get a list of all installed LanguageTool versions.
This method scans the download directory for LanguageTool installations and returns a list of LocalLanguageTool instances representing each version.
- Returns:
A list of installed LocalLanguageTool instances.
- Return type:
- classmethod get_latest_installed_version() LocalLanguageTool | None[source]¶
Get the latest installed LanguageTool version.
This method finds all installed versions and returns the most recent one according to version ordering.
- Returns:
The latest installed LocalLanguageTool instance, or None if no versions are installed.
- Return type:
LocalLanguageTool | None
- get_directory_path() Path[source]¶
Get the installation directory path for this LanguageTool version.
This method searches the download folder for the directory matching this version’s name.
- Returns:
The path to the LanguageTool installation directory.
- Return type:
- Raises:
FileNotFoundError – If the LanguageTool version directory is not found.
- get_jar_path() Path[source]¶
Get the path to the LanguageTool JAR file.
This method locates the main JAR file (languagetool-server.jar or languagetool.jar) within the installation directory.
- Returns:
The path to the LanguageTool JAR file.
- Return type:
- Raises:
FileNotFoundError – If no LanguageTool JAR file is found.
- get_server_cmd(port: int | None = None, config: LanguageToolConfig | None = None) list[str][source]¶
Generate the command to start the LanguageTool HTTP server.
- Parameters:
port (int | None) – Optional; The port number on which the server should run. If not provided, the default port will be used.
config (LanguageToolConfig | None) – Optional; The configuration for the LanguageTool server. If not provided, default configuration will be used.
- Returns:
A list of command line arguments to start the LanguageTool HTTP server.
- Return type:
- Raises:
JavaError – If the Java executable cannot be found.
FileNotFoundError – If the LanguageTool installation directory or JAR file cannot be found.
- abstract property version_name: str¶
Get the version name string.
This abstract property must be implemented by subclasses to return the version identifier.
- Returns:
The version name.
- Return type:
- Raises:
NotImplementedError – Always, unless implemented by a subclass.
- abstract property version_into: tuple[int, int] | datetime¶
Get the version as a comparable object.
This abstract property must be implemented by subclasses to return the version as either a tuple of integers (for releases) or datetime object (for snapshots) for comparison purposes.
- Returns:
A tuple of integers for releases or datetime for snapshots.
- Return type:
tuple[int, int] | datetime.datetime
- Raises:
NotImplementedError – Always, unless implemented by a subclass.
- abstract property download_url: str¶
Get the download URL for this LanguageTool version.
This abstract property must be implemented by subclasses to return the appropriate download URL.
- Returns:
The download URL.
- Return type:
- Raises:
NotImplementedError – Always, unless implemented by a subclass.
- class language_tool_python.download_lt.ReleaseLocalLanguageTool(version: str)[source]¶
Bases:
LocalLanguageToolRepresents a release version of LanguageTool.
This class handles release versions of LanguageTool (e.g., ‘6.0’, ‘5.9’) which are downloaded from the official release pages.
Releases are the old way of downloading LanguageTool.
- Parameters:
version (str) – The release version string (e.g., ‘6.0’).
- download() None[source]¶
Download and install this release version of LanguageTool.
This method checks Java compatibility, downloads the release ZIP file, and extracts it to the download folder if not already installed.
- Raises:
ModuleNotFoundError – If no Java installation is detected.
SystemError – If the detected Java version is incompatible.
TimeoutError – If the download request times out.
PathError – If the version is unsupported, the download fails, checksum validation fails, or ZIP extraction is unsafe.
- property version_name: str¶
Get the release version name.
- Returns:
The release version string.
- Return type:
- property download_url: str¶
Get the download URL for this release version.
URLs are constructed based on version: - Versions >= 6.7 are downloaded from the new release page - Versions 6.0 - 6.6 are downloaded from the main release page - Versions 4.0 - 5.9 are downloaded from the archive - Versions < 4.0 are not supported
- class language_tool_python.download_lt.SnapshotLocalLanguageTool(version_name: str)[source]¶
Bases:
LocalLanguageToolRepresents a snapshot (development) version of LanguageTool.
This class handles snapshot versions of LanguageTool, which are nightly builds identified by date strings (e.g., ‘20240101’) or ‘latest’.
Snapshots are the new common way of downloading LanguageTool.
- Parameters:
version_name (str) – The snapshot version (date string or ‘latest’).
- download() None[source]¶
Download and install this snapshot version of LanguageTool.
This method checks Java compatibility, downloads the snapshot ZIP file, and extracts it to the download folder using the requested snapshot name.
- Raises:
ModuleNotFoundError – If no Java installation is detected.
SystemError – If the detected Java version is incompatible.
TimeoutError – If the download request times out.
PathError – If the download fails, checksum validation fails, ZIP extraction is unsafe, or the extracted snapshot layout is invalid.
- property version_name: str¶
Get the snapshot version name.
Returns the current date if ‘latest’ was specified, otherwise returns the specified date string.
- Returns:
The snapshot version string.
- Return type:
- property version_into: datetime¶
Get the snapshot version as a datetime object for comparison.
Converts the version date string to a datetime object. For ‘latest’, uses the current date.
- Returns:
A datetime object representing the snapshot date.
- Return type:
- Raises:
ValueError – If the snapshot version is not a valid
YYYYMMDDdate.
Internal utilities - language_tool_python._internals¶
Only the types from this private module that surface in the public API are documented
here. CheckMatch in particular
appears in the Match constructor signature.
Note that if you have to perform type checking against CheckMatch (if you need to construct a Match manually, for example), you can use the function is_check_match() as a type guard (this function is in the public API). SupportsBool is also used in the public API, as it is in the alias type ConfigValue. Stuff from this module is not intended for public use, and may change or be removed without notice.
- class language_tool_python._internals.api_types.CheckMatch[source]¶
Bases:
TypedDictA raw match object returned by the LanguageTool check endpoint.
- replacements: list[Replacement]¶
- class language_tool_python._internals.api_types.Replacement[source]¶
Bases:
ReplacementOptionalA suggested replacement returned by LanguageTool.
- class language_tool_python._internals.api_types.Context[source]¶
Bases:
TypedDictText context around a LanguageTool match.
- class language_tool_python._internals.api_types.MatchType[source]¶
Bases:
TypedDictLanguageTool match type metadata.
- class language_tool_python._internals.api_types.Rule[source]¶
Bases:
RuleOptionalLanguageTool rule metadata for a match.