Skip to content

Commit 7f66d5b

Browse files
authored
Merge pull request jxmorris12#35 from aokellermann/feature/seassionOnlyNewSpellings
Session-only New Spellings
2 parents 6ac8f77 + e27935c commit 7f66d5b

2 files changed

Lines changed: 68 additions & 8 deletions

File tree

‎language_tool_python/server.py‎

Lines changed: 41 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,12 @@ class LanguageTool:
3333
_instances = WeakValueDictionary()
3434
_PORT_RE = re.compile(r"(?:https?://.*:|port\s+)(\d+)", re.I)
3535

36-
def __init__(self, language=None, motherTongue=None, remote_server=None, newSpellings=None):
36+
def __init__(self, language=None, motherTongue=None, remote_server=None, newSpellings=None, new_spellings_persist=True):
37+
self._new_spellings = None
38+
self._new_spellings_persist = new_spellings_persist
3739
if newSpellings:
38-
self._register_spellings(newSpellings)
40+
self._new_spellings = newSpellings
41+
self._register_spellings(self._new_spellings)
3942
if remote_server is not None:
4043
self._remote = True
4144
self._url = parse_url(remote_server)
@@ -57,14 +60,23 @@ def __init__(self, language=None, motherTongue=None, remote_server=None, newSpel
5760
self.enabled_rules_only = False
5861
self._instances[id(self)] = self
5962

60-
def __del__(self):
61-
if not self._instances and self._server_is_alive():
62-
self._terminate_server()
63+
def __enter__(self):
64+
return self
65+
66+
def __exit__(self, exc_type, exc_val, exc_tb):
67+
self.close()
6368

6469
def __repr__(self):
6570
return '{}(language={!r}, motherTongue={!r})'.format(
6671
self.__class__.__name__, self.language, self.motherTongue)
6772

73+
def close(self):
74+
if not self._instances and self._server_is_alive():
75+
self._terminate_server()
76+
if not self._new_spellings_persist and self._new_spellings:
77+
self._unregister_spellings()
78+
self._new_spellings = []
79+
6880
@property
6981
def language(self):
7082
"""The language to be used."""
@@ -126,14 +138,35 @@ def disable_spellchecking(self):
126138
"""Disable spell-checking rules."""
127139
self.disabled_categories.update(self._spell_checking_categories)
128140

129-
def _register_spellings(self, spellings):
141+
@staticmethod
142+
def _get_valid_spelling_file_path() -> str:
130143
library_path = get_language_tool_directory()
131144
spelling_file_path = os.path.join(library_path, "org/languagetool/resource/en/hunspell/spelling.txt")
132145
if not os.path.exists(spelling_file_path):
133-
raise FileNotFoundError("Failed to find the spellings file at {}\n Please file an issue at https://github.com/jxmorris12/language_tool_python".format(spelling_file_path))
146+
raise FileNotFoundError("Failed to find the spellings file at {}\n Please file an issue at "
147+
"https://github.com/jxmorris12/language_tool_python/issues"
148+
.format(spelling_file_path))
149+
return spelling_file_path
150+
151+
def _register_spellings(self, spellings):
152+
spelling_file_path = self._get_valid_spelling_file_path()
134153
with open(spelling_file_path, "a+") as spellings_file:
135154
spellings_file.write("\n" + "\n".join([word for word in spellings]))
136-
print("Updated the spellings at {}".format(spelling_file_path))
155+
if DEBUG_MODE:
156+
print("Registered new spellings at {}".format(spelling_file_path))
157+
158+
def _unregister_spellings(self):
159+
spelling_file_path = self._get_valid_spelling_file_path()
160+
with open(spelling_file_path, 'r+') as spellings_file:
161+
spellings_file.seek(0, os.SEEK_END)
162+
for _ in range(len(self._new_spellings)):
163+
while spellings_file.read(1) != '\n':
164+
spellings_file.seek(spellings_file.tell() - 2, os.SEEK_SET)
165+
spellings_file.seek(spellings_file.tell() - 2, os.SEEK_SET)
166+
spellings_file.seek(spellings_file.tell() + 1, os.SEEK_SET)
167+
spellings_file.truncate()
168+
if DEBUG_MODE:
169+
print("Unregistered new spellings at {}".format(spelling_file_path))
137170

138171
def _get_languages(self) -> set:
139172
"""Get supported languages (by querying the server)."""

‎tests/test_major_functionality.py‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,33 @@ def test_spellcheck_en_gb():
5959
tool.disable_spellchecking()
6060
assert tool.correct(s) == "Wat is wrong with the spll chker"
6161

62+
def test_session_only_new_spellings():
63+
import os
64+
import hashlib
65+
import language_tool_python
66+
library_path = language_tool_python.utils.get_language_tool_directory()
67+
spelling_file_path = os.path.join(library_path, "org/languagetool/resource/en/hunspell/spelling.txt")
68+
with open(spelling_file_path, 'r') as spelling_file:
69+
initial_spelling_file_contents = spelling_file.read()
70+
initial_checksum = hashlib.sha256(initial_spelling_file_contents.encode())
71+
72+
new_spellings = ["word1", "word2", "word3"]
73+
with language_tool_python.LanguageTool('en-US', newSpellings=new_spellings, new_spellings_persist=False) as tool:
74+
tool.enabled_rules_only = True
75+
tool.enabled_rules = {'MORFOLOGIK_RULE_EN_US'}
76+
matches = tool.check(" ".join(new_spellings))
77+
78+
with open(spelling_file_path, 'r') as spelling_file:
79+
subsequent_spelling_file_contents = spelling_file.read()
80+
subsequent_checksum = hashlib.sha256(subsequent_spelling_file_contents.encode())
81+
82+
if initial_checksum != subsequent_checksum:
83+
with open(spelling_file_path, 'w') as spelling_file:
84+
spelling_file.write(initial_spelling_file_contents)
85+
86+
assert not matches
87+
assert initial_checksum.hexdigest() == subsequent_checksum.hexdigest()
88+
6289
def test_debug_mode():
6390
from language_tool_python.server import DEBUG_MODE
6491
assert DEBUG_MODE is False

0 commit comments

Comments
 (0)