Coverage for src/mkdocs_spellcheck/backends/symspellpy.py: 0.00%

23 statements  

« prev     ^ index     » next       coverage.py v7.4.4, created at 2024-05-05 19:28 +0200

1"""Backend for the `symspellpy` library.""" 

2 

3from __future__ import annotations 

4 

5import sys 

6from typing import TYPE_CHECKING, Any 

7 

8from symspellpy import SymSpell, Verbosity 

9 

10from mkdocs_spellcheck.backends import Backend 

11from mkdocs_spellcheck.loggers import get_plugin_logger 

12 

13if sys.version_info < (3, 9): 

14 import importlib_resources as resources 

15else: 

16 from importlib import resources 

17 

18if TYPE_CHECKING: 

19 from mkdocs.structure.pages import Page 

20 

21logger = get_plugin_logger(__name__) 

22 

23 

24class SymspellpyBackend(Backend): 

25 """Backend for the `symspellpy` library.""" 

26 

27 def __init__(self, config: dict[str, Any], known_words: set[str] | None = None) -> None: # noqa: ARG002 

28 """Initialize the `symspellpy` backend. 

29 

30 This backend needs to load dictionaries provided 

31 by `symspellpy` itself. 

32 

33 Parameters: 

34 config: User configuration from `mkdocs.yml`. 

35 known_words: Globally known words. 

36 """ 

37 self.spell = SymSpell() 

38 dictionary_res = resources.files("symspellpy").joinpath("frequency_dictionary_en_82_765.txt") 

39 with resources.as_file(dictionary_res) as dictionary_path: 

40 self.spell.load_dictionary(dictionary_path, 0, 1) 

41 

42 def check(self, page: Page, word: str) -> None: # noqa: D102 

43 suggestions = self.spell.lookup(word, Verbosity.CLOSEST, max_edit_distance=2) 

44 if suggestions: 

45 candidates = "', '".join(suggestion.term for suggestion in suggestions if suggestion.term != word) 

46 if candidates: 

47 logger.warning(f"(symspellpy) {page.file.src_path}: Misspelled '{word}', did you mean '{candidates}'?") 

48 else: 

49 logger.warning(f"(symspellpy) {page.file.src_path}: Misspelled '{word}', no suggestions")