kotoshu 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
kotoshu-0.1.0/LICENSE ADDED
@@ -0,0 +1,26 @@
1
+ BSD 2-Clause License
2
+
3
+ Copyright (c) 2025-2026, Kotoshu contributors
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ 1. Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ 2. Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
20
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
22
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
23
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26
+
kotoshu-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,123 @@
1
+ Metadata-Version: 2.4
2
+ Name: kotoshu
3
+ Version: 0.1.0
4
+ Summary: Python client for the Kotoshu HTTP spell-check API
5
+ Author-email: "Ribose Inc." <open.source@ribose.com>
6
+ License: BSD-2-Clause
7
+ Project-URL: Homepage, https://github.com/kotoshu/kotoshu-python
8
+ Project-URL: Source, https://github.com/kotoshu/kotoshu-python
9
+ Classifier: License :: OSI Approved :: BSD License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Topic :: Text Processing
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: requests>=2.28
16
+ Provides-Extra: native
17
+ Requires-Dist: kotoshu-native; extra == "native"
18
+ Dynamic: license-file
19
+
20
+ # kotoshu-python
21
+
22
+ Python client for the [Kotoshu](https://github.com/kotoshu/kotoshu) HTTP
23
+ spell-check API.
24
+
25
+ ## Install
26
+
27
+ ```bash
28
+ pip install kotoshu
29
+ ```
30
+
31
+ ## Quick start
32
+
33
+ ```python
34
+ from kotoshu import Client
35
+
36
+ client = Client("http://localhost:9292")
37
+
38
+ # Check a document
39
+ result = client.check("helo wrold", language="en")
40
+ for err in result.errors:
41
+ print(f"{err.word} -> {err.top_suggestions}")
42
+
43
+ # Suggestions for one word
44
+ for sug in client.suggest("helo", max_suggestions=3):
45
+ print(sug.word, sug.confidence)
46
+
47
+ # Language detection
48
+ det = client.detect("bonjour le monde")
49
+ print(det.language, det.confidence)
50
+ ```
51
+
52
+ ## Reference
53
+
54
+ ### `Client(base_url, *, language="en", timeout=30.0, session=None)`
55
+
56
+ - `health() -> dict`
57
+ - `languages() -> list[str]`
58
+ - `check(text, *, language=None, fmt="full") -> DocumentResult`
59
+ - `suggest(word, *, language=None, max_suggestions=None) -> list[Suggestion]`
60
+ - `detect(text) -> Detection`
61
+ - `correct(word, *, language=None) -> bool`
62
+
63
+ ### Result types
64
+
65
+ - `DocumentResult`: `file`, `word_count`, `errors: list[WordError]`, `success`, `misspelled_words`
66
+ - `WordError`: `word`, `position`, `suggestions: list[Suggestion]`, `top_suggestions`
67
+ - `Suggestion`: `word`, `distance`, `confidence`, `source`, `metadata`
68
+ - `Detection`: `language`, `confidence`
69
+
70
+ ### Exceptions
71
+
72
+ - `KotoshuError`: base
73
+ - `ResourceNotSetupError`: server returned 422 — language not set up
74
+
75
+ ## Native backend (optional, offline)
76
+
77
+ `kotoshu` can also spell-check fully offline through the native Rust
78
+ engine instead of the HTTP API. The engine ships in the
79
+ [`kotoshu-native`](https://github.com/kotoshu/kotoshu-rs) wheel (module
80
+ `kotoshu_native`) and works on local Hunspell dictionaries:
81
+
82
+ ```python
83
+ from kotoshu.native import dictionary
84
+
85
+ d = dictionary("en_US.aff", "en_US.dic")
86
+ d.correct("hello") # True
87
+ d.suggest("hlelo", max_suggestions=3) # [Suggestion(word="hello", ...)]
88
+ ```
89
+
90
+ `Dictionary.correct`/`suggest` return exactly the same types as the HTTP
91
+ `Client` (`bool` and `list[Suggestion]`), so result handling is identical
92
+ across backends. The offline engine is word-level only: no document
93
+ parsing, no language detection.
94
+
95
+ ### `KOTOSHU_BACKEND`
96
+
97
+ - `auto` (default): native when `kotoshu_native` is importable, else HTTP
98
+ - `native`: require the native engine (`NativeUnavailableError` when missing)
99
+ - `http`: always the HTTP API
100
+
101
+ `kotoshu.backend()` reports the backend in effect (`"native"` or
102
+ `"http"`); `kotoshu.native.available()` whether the wheel is importable.
103
+
104
+ ### Getting the wheel
105
+
106
+ The `kotoshu-native` wheel is **not published to PyPI yet** (publishing
107
+ is blocked on owner credentials), so `pip install kotoshu[native]`
108
+ resolves only after that first publish. Until then build it locally from
109
+ the [kotoshu-rs](https://github.com/kotoshu/kotoshu-rs) repository:
110
+
111
+ ```bash
112
+ python3 -m venv .venv && . .venv/bin/activate
113
+ pip install maturin
114
+ cd /path/to/kotoshu-rs/kotoshu-python
115
+ maturin develop
116
+ ```
117
+
118
+ Without the wheel nothing changes: `auto` silently uses HTTP and the
119
+ client behaves exactly as before.
120
+
121
+ ## License
122
+
123
+ BSD-2-Clause, same as Kotoshu.
@@ -0,0 +1,104 @@
1
+ # kotoshu-python
2
+
3
+ Python client for the [Kotoshu](https://github.com/kotoshu/kotoshu) HTTP
4
+ spell-check API.
5
+
6
+ ## Install
7
+
8
+ ```bash
9
+ pip install kotoshu
10
+ ```
11
+
12
+ ## Quick start
13
+
14
+ ```python
15
+ from kotoshu import Client
16
+
17
+ client = Client("http://localhost:9292")
18
+
19
+ # Check a document
20
+ result = client.check("helo wrold", language="en")
21
+ for err in result.errors:
22
+ print(f"{err.word} -> {err.top_suggestions}")
23
+
24
+ # Suggestions for one word
25
+ for sug in client.suggest("helo", max_suggestions=3):
26
+ print(sug.word, sug.confidence)
27
+
28
+ # Language detection
29
+ det = client.detect("bonjour le monde")
30
+ print(det.language, det.confidence)
31
+ ```
32
+
33
+ ## Reference
34
+
35
+ ### `Client(base_url, *, language="en", timeout=30.0, session=None)`
36
+
37
+ - `health() -> dict`
38
+ - `languages() -> list[str]`
39
+ - `check(text, *, language=None, fmt="full") -> DocumentResult`
40
+ - `suggest(word, *, language=None, max_suggestions=None) -> list[Suggestion]`
41
+ - `detect(text) -> Detection`
42
+ - `correct(word, *, language=None) -> bool`
43
+
44
+ ### Result types
45
+
46
+ - `DocumentResult`: `file`, `word_count`, `errors: list[WordError]`, `success`, `misspelled_words`
47
+ - `WordError`: `word`, `position`, `suggestions: list[Suggestion]`, `top_suggestions`
48
+ - `Suggestion`: `word`, `distance`, `confidence`, `source`, `metadata`
49
+ - `Detection`: `language`, `confidence`
50
+
51
+ ### Exceptions
52
+
53
+ - `KotoshuError`: base
54
+ - `ResourceNotSetupError`: server returned 422 — language not set up
55
+
56
+ ## Native backend (optional, offline)
57
+
58
+ `kotoshu` can also spell-check fully offline through the native Rust
59
+ engine instead of the HTTP API. The engine ships in the
60
+ [`kotoshu-native`](https://github.com/kotoshu/kotoshu-rs) wheel (module
61
+ `kotoshu_native`) and works on local Hunspell dictionaries:
62
+
63
+ ```python
64
+ from kotoshu.native import dictionary
65
+
66
+ d = dictionary("en_US.aff", "en_US.dic")
67
+ d.correct("hello") # True
68
+ d.suggest("hlelo", max_suggestions=3) # [Suggestion(word="hello", ...)]
69
+ ```
70
+
71
+ `Dictionary.correct`/`suggest` return exactly the same types as the HTTP
72
+ `Client` (`bool` and `list[Suggestion]`), so result handling is identical
73
+ across backends. The offline engine is word-level only: no document
74
+ parsing, no language detection.
75
+
76
+ ### `KOTOSHU_BACKEND`
77
+
78
+ - `auto` (default): native when `kotoshu_native` is importable, else HTTP
79
+ - `native`: require the native engine (`NativeUnavailableError` when missing)
80
+ - `http`: always the HTTP API
81
+
82
+ `kotoshu.backend()` reports the backend in effect (`"native"` or
83
+ `"http"`); `kotoshu.native.available()` whether the wheel is importable.
84
+
85
+ ### Getting the wheel
86
+
87
+ The `kotoshu-native` wheel is **not published to PyPI yet** (publishing
88
+ is blocked on owner credentials), so `pip install kotoshu[native]`
89
+ resolves only after that first publish. Until then build it locally from
90
+ the [kotoshu-rs](https://github.com/kotoshu/kotoshu-rs) repository:
91
+
92
+ ```bash
93
+ python3 -m venv .venv && . .venv/bin/activate
94
+ pip install maturin
95
+ cd /path/to/kotoshu-rs/kotoshu-python
96
+ maturin develop
97
+ ```
98
+
99
+ Without the wheel nothing changes: `auto` silently uses HTTP and the
100
+ client behaves exactly as before.
101
+
102
+ ## License
103
+
104
+ BSD-2-Clause, same as Kotoshu.
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "kotoshu"
7
+ version = "0.1.0"
8
+ description = "Python client for the Kotoshu HTTP spell-check API"
9
+ readme = "README.md"
10
+ license = { text = "BSD-2-Clause" }
11
+ authors = [{ name = "Ribose Inc.", email = "open.source@ribose.com" }]
12
+ requires-python = ">=3.10"
13
+ dependencies = ["requests>=2.28"]
14
+ classifiers = [
15
+ "License :: OSI Approved :: BSD License",
16
+ "Programming Language :: Python :: 3",
17
+ "Topic :: Text Processing",
18
+ ]
19
+
20
+ # The `native` extra resolves only once the `kotoshu-native` wheel is
21
+ # published to PyPI (blocked on owner credentials; see README "Native
22
+ # backend"). Until then build it locally with `maturin develop` inside
23
+ # kotoshu-rs/kotoshu-python.
24
+ [project.optional-dependencies]
25
+ native = ["kotoshu-native"]
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/kotoshu/kotoshu-python"
29
+ Source = "https://github.com/kotoshu/kotoshu-python"
30
+
31
+ [tool.setuptools.packages.find]
32
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,187 @@
1
+ """Kotoshu HTTP API client.
2
+
3
+ Thin sync client for the kotoshu-server HTTP API.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ from dataclasses import dataclass, field
10
+ from typing import Any, Iterable
11
+
12
+ try:
13
+ import requests
14
+ except ImportError as exc: # pragma: no cover
15
+ raise ImportError(
16
+ "kotoshu requires 'requests'; install with: pip install kotoshu"
17
+ ) from exc
18
+
19
+
20
+ @dataclass
21
+ class Suggestion:
22
+ word: str
23
+ distance: int = 0
24
+ confidence: float = 1.0
25
+ source: str = "unknown"
26
+ metadata: dict = field(default_factory=dict)
27
+
28
+
29
+ @dataclass
30
+ class WordError:
31
+ word: str
32
+ position: int | None
33
+ suggestions: list[Suggestion] = field(default_factory=list)
34
+
35
+ @property
36
+ def top_suggestions(self) -> list[str]:
37
+ return [s.word for s in self.suggestions[:3]]
38
+
39
+
40
+ @dataclass
41
+ class DocumentResult:
42
+ file: str | None
43
+ word_count: int
44
+ errors: list[WordError] = field(default_factory=list)
45
+
46
+ @property
47
+ def success(self) -> bool:
48
+ return not self.errors
49
+
50
+ @property
51
+ def misspelled_words(self) -> list[str]:
52
+ return [e.word for e in self.errors]
53
+
54
+
55
+ @dataclass
56
+ class Detection:
57
+ language: str | None
58
+ confidence: float
59
+
60
+
61
+ class KotoshuError(Exception):
62
+ """Raised when the kotoshu server returns an error."""
63
+
64
+
65
+ class ResourceNotSetupError(KotoshuError):
66
+ """The requested language is not set up on the server."""
67
+
68
+
69
+ class Client:
70
+ """Sync client for the kotoshu-server HTTP API.
71
+
72
+ Args:
73
+ base_url: Base URL, e.g. "http://localhost:9292".
74
+ language: Default language code; can be overridden per call.
75
+ timeout: HTTP timeout in seconds.
76
+ session: Optional requests.Session for connection pooling.
77
+ """
78
+
79
+ def __init__(
80
+ self,
81
+ base_url: str = "http://localhost:9292",
82
+ *,
83
+ language: str = "en",
84
+ timeout: float = 30.0,
85
+ session: requests.Session | None = None,
86
+ ) -> None:
87
+ self.base_url = base_url.rstrip("/")
88
+ self.default_language = language
89
+ self.timeout = timeout
90
+ self.session = session or requests.Session()
91
+
92
+ def health(self) -> dict[str, Any]:
93
+ return self._get("/v1/health")
94
+
95
+ def languages(self) -> list[str]:
96
+ return self._get("/v1/languages").get("cached", [])
97
+
98
+ def check(
99
+ self,
100
+ text: str,
101
+ *,
102
+ language: str | None = None,
103
+ fmt: str = "full",
104
+ ) -> DocumentResult:
105
+ body = {"text": text, "language": language or self.default_language, "format": fmt}
106
+ raw = self._post("/v1/check", body)
107
+ return DocumentResult(
108
+ file=raw.get("file"),
109
+ word_count=raw.get("word_count", 0),
110
+ errors=[
111
+ WordError(
112
+ word=e["word"],
113
+ position=e.get("position"),
114
+ suggestions=[Suggestion(**s) for s in e.get("suggestions", [])],
115
+ )
116
+ for e in raw.get("errors", [])
117
+ ],
118
+ )
119
+
120
+ def suggest(
121
+ self,
122
+ word: str,
123
+ *,
124
+ language: str | None = None,
125
+ max_suggestions: int | None = None,
126
+ ) -> list[Suggestion]:
127
+ body: dict[str, Any] = {"word": word, "language": language or self.default_language}
128
+ if max_suggestions is not None:
129
+ body["max"] = max_suggestions
130
+ raw = self._post("/v1/suggest", body)
131
+ return [Suggestion(**s) for s in raw.get("suggestions", [])]
132
+
133
+ def detect(self, text: str) -> Detection:
134
+ raw = self._post("/v1/detect", {"text": text})
135
+ return Detection(language=raw.get("language"), confidence=raw.get("confidence", 0.0))
136
+
137
+ def correct(self, word: str, *, language: str | None = None) -> bool:
138
+ """Return True if `word` is in the dictionary (no errors)."""
139
+ result = self.check(word, language=language)
140
+ return result.success
141
+
142
+ # ---- Internals ----
143
+
144
+ def _get(self, path: str) -> Any:
145
+ url = self.base_url + path
146
+ resp = self.session.get(url, timeout=self.timeout)
147
+ return self._handle(resp)
148
+
149
+ def _post(self, path: str, body: dict[str, Any]) -> Any:
150
+ url = self.base_url + path
151
+ resp = self.session.post(url, json=body, timeout=self.timeout)
152
+ return self._handle(resp)
153
+
154
+ @staticmethod
155
+ def _handle(resp: requests.Response) -> Any:
156
+ try:
157
+ data = resp.json()
158
+ except (ValueError, json.JSONDecodeError) as exc:
159
+ raise KotoshuError(
160
+ f"non-JSON response from server (status={resp.status_code}): {resp.text[:200]}"
161
+ ) from exc
162
+ if 200 <= resp.status_code < 300:
163
+ return data
164
+ err = data.get("error", "http_error")
165
+ msg = data.get("message", resp.text)
166
+ if err == "resource_not_setup":
167
+ raise ResourceNotSetupError(msg)
168
+ raise KotoshuError(f"{err}: {msg}")
169
+
170
+
171
+ # Imported at the bottom: kotoshu.native imports the dataclasses and
172
+ # error types defined above from this module, so they must exist first.
173
+ from .native import NativeBackend, NativeUnavailableError, backend
174
+
175
+
176
+ __all__ = [
177
+ "Client",
178
+ "DocumentResult",
179
+ "WordError",
180
+ "Suggestion",
181
+ "Detection",
182
+ "KotoshuError",
183
+ "ResourceNotSetupError",
184
+ "NativeBackend",
185
+ "NativeUnavailableError",
186
+ "backend",
187
+ ]
@@ -0,0 +1,191 @@
1
+ """Optional native (Rust) engine backend.
2
+
3
+ Wraps the ``kotoshu_native`` extension module -- the ``kotoshu-native``
4
+ wheel built from the kotoshu-rs repository -- behind the same result
5
+ shapes the HTTP client returns, so ``Suggestion`` objects are identical
6
+ across backends.
7
+
8
+ The wheel is not published to PyPI yet (blocked on owner credentials),
9
+ so a plain ``pip install kotoshu`` has no native engine: ``available()``
10
+ is False and the default ``auto`` backend quietly falls back to HTTP.
11
+ Build the module locally to use it today (see README, "Native backend").
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import os
17
+ from types import ModuleType
18
+ from typing import Any
19
+
20
+ from . import KotoshuError, Suggestion
21
+
22
+ try:
23
+ import kotoshu_native as _native
24
+ except ImportError: # the wheel is not installed; see module docstring
25
+ _native = None
26
+
27
+ #: Environment variable selecting the backend: "native", "http" or "auto".
28
+ ENV_VAR = "KOTOSHU_BACKEND"
29
+
30
+ NATIVE = "native"
31
+ HTTP = "http"
32
+ AUTO = "auto"
33
+
34
+ _UNAVAILABLE_MESSAGE = (
35
+ "the native backend was requested (KOTOSHU_BACKEND=native) but the "
36
+ "'kotoshu_native' extension module could not be imported.\n"
37
+ "The 'kotoshu-native' wheel is not published to PyPI yet (pending "
38
+ "credentials); until then build it locally from the kotoshu-rs "
39
+ "repository:\n"
40
+ " python3 -m venv .venv && . .venv/bin/activate\n"
41
+ " pip install maturin\n"
42
+ " maturin develop # inside kotoshu-rs/kotoshu-python\n"
43
+ "Or keep using the HTTP backend: KOTOSHU_BACKEND=http"
44
+ )
45
+
46
+
47
+ class NativeUnavailableError(KotoshuError):
48
+ """The native backend was requested but kotoshu_native is missing."""
49
+
50
+
51
+ def available() -> bool:
52
+ """Return True when the kotoshu_native extension module is importable."""
53
+ return _native is not None
54
+
55
+
56
+ def resolve_backend(setting: str | None, native_available: bool) -> str:
57
+ """Resolve a KOTOSHU_BACKEND value to "native" or "http".
58
+
59
+ Pure decision function (no environment, no imports): `setting` is the
60
+ raw env value (None or empty means "auto"), `native_available` is
61
+ whether kotoshu_native imports. Raises NativeUnavailableError when
62
+ "native" is forced but unavailable, ValueError for anything else.
63
+ """
64
+ choice = (setting or AUTO).strip().lower()
65
+ if choice == AUTO:
66
+ return NATIVE if native_available else HTTP
67
+ if choice == HTTP:
68
+ return HTTP
69
+ if choice == NATIVE:
70
+ if not native_available:
71
+ raise NativeUnavailableError(_UNAVAILABLE_MESSAGE)
72
+ return NATIVE
73
+ raise ValueError(
74
+ f"invalid {ENV_VAR}={setting!r}: expected 'native', 'http' or 'auto'"
75
+ )
76
+
77
+
78
+ def backend() -> str:
79
+ """Return the backend in effect: "native" or "http".
80
+
81
+ Honors KOTOSHU_BACKEND (native|http|auto; default auto: native when
82
+ the wheel is importable, else http). Raises NativeUnavailableError
83
+ when "native" is forced but the module is missing.
84
+ """
85
+ return resolve_backend(os.environ.get(ENV_VAR), available())
86
+
87
+
88
+ class Dictionary:
89
+ """A loaded native dictionary -- the offline twin of ``Client``.
90
+
91
+ Instances are created by :meth:`load` or
92
+ ``NativeBackend.dictionary``. ``correct``/``suggest`` return exactly
93
+ the shapes the HTTP client returns, so result handling is identical
94
+ across backends. Word-level only: the offline engine has no document
95
+ parsing and no language detection.
96
+ """
97
+
98
+ def __init__(self, module: ModuleType, impl: Any) -> None:
99
+ self._module = module
100
+ self._impl = impl
101
+
102
+ @classmethod
103
+ def load(cls, aff_path: str, dic_path: str) -> Dictionary:
104
+ """Load Hunspell .aff/.dic files through the native engine."""
105
+ return _load_via(_required_module(), aff_path, dic_path)
106
+
107
+ def correct(self, word: str) -> bool:
108
+ """Return True if `word` is in the dictionary (no errors)."""
109
+ try:
110
+ return bool(self._impl.correct(word))
111
+ except self._module.KotoshuNativeError as exc:
112
+ raise KotoshuError(f"native check failed: {exc}") from exc
113
+
114
+ def suggest(
115
+ self,
116
+ word: str,
117
+ *,
118
+ max_suggestions: int = 5,
119
+ ) -> list[Suggestion]:
120
+ """Return suggestions for `word`, same Suggestion type as the client."""
121
+ try:
122
+ rows = self._impl.suggest(word, max_suggestions)
123
+ except self._module.KotoshuNativeError as exc:
124
+ raise KotoshuError(f"native suggest failed: {exc}") from exc
125
+ return [Suggestion(**row) for row in rows]
126
+
127
+
128
+ class NativeBackend:
129
+ """Facade over the kotoshu_native extension module.
130
+
131
+ Constructing one without the wheel raises NativeUnavailableError
132
+ with instructions (see the module docstring and README).
133
+ """
134
+
135
+ def __init__(self) -> None:
136
+ self._module = _required_module()
137
+
138
+ @property
139
+ def VERSION(self) -> str:
140
+ """The kotoshu_native module version string."""
141
+ return self._module.VERSION
142
+
143
+ @staticmethod
144
+ def available() -> bool:
145
+ """Return True when the kotoshu_native extension module is importable."""
146
+ return available()
147
+
148
+ def dictionary(self, aff_path: str, dic_path: str) -> Dictionary:
149
+ """Load Hunspell .aff/.dic files into a native Dictionary."""
150
+ return _load_via(self._module, aff_path, dic_path)
151
+
152
+
153
+ def dictionary(aff_path: str, dic_path: str) -> Dictionary:
154
+ """Load a native dictionary; the offline spell-check entry point.
155
+
156
+ Convenience for ``NativeBackend().dictionary(...)``; raises
157
+ NativeUnavailableError when the wheel is not importable.
158
+ """
159
+ return NativeBackend().dictionary(aff_path, dic_path)
160
+
161
+
162
+ # ---- Internals ----
163
+
164
+
165
+ def _required_module() -> ModuleType:
166
+ if _native is None:
167
+ raise NativeUnavailableError(_UNAVAILABLE_MESSAGE)
168
+ return _native
169
+
170
+
171
+ def _load_via(module: ModuleType, aff_path: str, dic_path: str) -> Dictionary:
172
+ try:
173
+ impl = module.Dictionary.load(aff_path, dic_path)
174
+ except module.KotoshuNativeError as exc:
175
+ raise KotoshuError(f"loading native dictionary failed: {exc}") from exc
176
+ return Dictionary(module, impl)
177
+
178
+
179
+ __all__ = [
180
+ "AUTO",
181
+ "ENV_VAR",
182
+ "HTTP",
183
+ "NATIVE",
184
+ "Dictionary",
185
+ "NativeBackend",
186
+ "NativeUnavailableError",
187
+ "available",
188
+ "backend",
189
+ "dictionary",
190
+ "resolve_backend",
191
+ ]
@@ -0,0 +1,123 @@
1
+ Metadata-Version: 2.4
2
+ Name: kotoshu
3
+ Version: 0.1.0
4
+ Summary: Python client for the Kotoshu HTTP spell-check API
5
+ Author-email: "Ribose Inc." <open.source@ribose.com>
6
+ License: BSD-2-Clause
7
+ Project-URL: Homepage, https://github.com/kotoshu/kotoshu-python
8
+ Project-URL: Source, https://github.com/kotoshu/kotoshu-python
9
+ Classifier: License :: OSI Approved :: BSD License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Topic :: Text Processing
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: requests>=2.28
16
+ Provides-Extra: native
17
+ Requires-Dist: kotoshu-native; extra == "native"
18
+ Dynamic: license-file
19
+
20
+ # kotoshu-python
21
+
22
+ Python client for the [Kotoshu](https://github.com/kotoshu/kotoshu) HTTP
23
+ spell-check API.
24
+
25
+ ## Install
26
+
27
+ ```bash
28
+ pip install kotoshu
29
+ ```
30
+
31
+ ## Quick start
32
+
33
+ ```python
34
+ from kotoshu import Client
35
+
36
+ client = Client("http://localhost:9292")
37
+
38
+ # Check a document
39
+ result = client.check("helo wrold", language="en")
40
+ for err in result.errors:
41
+ print(f"{err.word} -> {err.top_suggestions}")
42
+
43
+ # Suggestions for one word
44
+ for sug in client.suggest("helo", max_suggestions=3):
45
+ print(sug.word, sug.confidence)
46
+
47
+ # Language detection
48
+ det = client.detect("bonjour le monde")
49
+ print(det.language, det.confidence)
50
+ ```
51
+
52
+ ## Reference
53
+
54
+ ### `Client(base_url, *, language="en", timeout=30.0, session=None)`
55
+
56
+ - `health() -> dict`
57
+ - `languages() -> list[str]`
58
+ - `check(text, *, language=None, fmt="full") -> DocumentResult`
59
+ - `suggest(word, *, language=None, max_suggestions=None) -> list[Suggestion]`
60
+ - `detect(text) -> Detection`
61
+ - `correct(word, *, language=None) -> bool`
62
+
63
+ ### Result types
64
+
65
+ - `DocumentResult`: `file`, `word_count`, `errors: list[WordError]`, `success`, `misspelled_words`
66
+ - `WordError`: `word`, `position`, `suggestions: list[Suggestion]`, `top_suggestions`
67
+ - `Suggestion`: `word`, `distance`, `confidence`, `source`, `metadata`
68
+ - `Detection`: `language`, `confidence`
69
+
70
+ ### Exceptions
71
+
72
+ - `KotoshuError`: base
73
+ - `ResourceNotSetupError`: server returned 422 — language not set up
74
+
75
+ ## Native backend (optional, offline)
76
+
77
+ `kotoshu` can also spell-check fully offline through the native Rust
78
+ engine instead of the HTTP API. The engine ships in the
79
+ [`kotoshu-native`](https://github.com/kotoshu/kotoshu-rs) wheel (module
80
+ `kotoshu_native`) and works on local Hunspell dictionaries:
81
+
82
+ ```python
83
+ from kotoshu.native import dictionary
84
+
85
+ d = dictionary("en_US.aff", "en_US.dic")
86
+ d.correct("hello") # True
87
+ d.suggest("hlelo", max_suggestions=3) # [Suggestion(word="hello", ...)]
88
+ ```
89
+
90
+ `Dictionary.correct`/`suggest` return exactly the same types as the HTTP
91
+ `Client` (`bool` and `list[Suggestion]`), so result handling is identical
92
+ across backends. The offline engine is word-level only: no document
93
+ parsing, no language detection.
94
+
95
+ ### `KOTOSHU_BACKEND`
96
+
97
+ - `auto` (default): native when `kotoshu_native` is importable, else HTTP
98
+ - `native`: require the native engine (`NativeUnavailableError` when missing)
99
+ - `http`: always the HTTP API
100
+
101
+ `kotoshu.backend()` reports the backend in effect (`"native"` or
102
+ `"http"`); `kotoshu.native.available()` whether the wheel is importable.
103
+
104
+ ### Getting the wheel
105
+
106
+ The `kotoshu-native` wheel is **not published to PyPI yet** (publishing
107
+ is blocked on owner credentials), so `pip install kotoshu[native]`
108
+ resolves only after that first publish. Until then build it locally from
109
+ the [kotoshu-rs](https://github.com/kotoshu/kotoshu-rs) repository:
110
+
111
+ ```bash
112
+ python3 -m venv .venv && . .venv/bin/activate
113
+ pip install maturin
114
+ cd /path/to/kotoshu-rs/kotoshu-python
115
+ maturin develop
116
+ ```
117
+
118
+ Without the wheel nothing changes: `auto` silently uses HTTP and the
119
+ client behaves exactly as before.
120
+
121
+ ## License
122
+
123
+ BSD-2-Clause, same as Kotoshu.
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/kotoshu/__init__.py
5
+ src/kotoshu/native.py
6
+ src/kotoshu.egg-info/PKG-INFO
7
+ src/kotoshu.egg-info/SOURCES.txt
8
+ src/kotoshu.egg-info/dependency_links.txt
9
+ src/kotoshu.egg-info/requires.txt
10
+ src/kotoshu.egg-info/top_level.txt
11
+ tests/test_client.py
12
+ tests/test_native.py
@@ -0,0 +1,4 @@
1
+ requests>=2.28
2
+
3
+ [native]
4
+ kotoshu-native
@@ -0,0 +1 @@
1
+ kotoshu
@@ -0,0 +1,64 @@
1
+ """Smoke test against a live kotoshu-server.
2
+
3
+ Run with: python -m pytest tests/test_client.py
4
+ Set KOTOSHU_TEST_URL to point at a different server.
5
+ """
6
+
7
+ import os
8
+
9
+ import pytest
10
+
11
+ from kotoshu import Client, DocumentResult, KotoshuError
12
+
13
+
14
+ @pytest.fixture(scope="module")
15
+ def client():
16
+ url = os.environ.get("KOTOSHU_TEST_URL", "http://localhost:9292")
17
+ c = Client(url)
18
+ try:
19
+ c.health()
20
+ except Exception as exc:
21
+ pytest.skip(f"no kotoshu server at {url}: {exc}")
22
+ return c
23
+
24
+
25
+ def test_check_flags_misspelled(client):
26
+ result = client.check("helo wrold", language="en")
27
+ assert isinstance(result, DocumentResult)
28
+ assert "helo" in result.misspelled_words
29
+ assert "wrold" in result.misspelled_words
30
+
31
+
32
+ def test_check_passes_correct_text(client):
33
+ result = client.check("hello world", language="en")
34
+ assert result.success
35
+ assert result.misspelled_words == []
36
+
37
+
38
+ def test_suggest_returns_suggestions(client):
39
+ suggestions = client.suggest("helo", language="en", max_suggestions=3)
40
+ assert len(suggestions) <= 3
41
+ assert any(s.word == "hello" for s in suggestions)
42
+
43
+
44
+ def test_detect_returns_language(client):
45
+ detection = client.detect("hello world")
46
+ assert detection.language is not None
47
+ assert 0.0 <= detection.confidence <= 1.0
48
+
49
+
50
+ def test_correct_helper(client):
51
+ assert client.correct("hello", language="en") is True
52
+ assert client.correct("helo", language="en") is False
53
+
54
+
55
+ def test_languages_endpoint(client):
56
+ langs = client.languages()
57
+ assert isinstance(langs, list)
58
+ assert "en" in langs
59
+
60
+
61
+ def test_error_on_missing_text(client):
62
+ with pytest.raises(KotoshuError):
63
+ # Bypass client-side validation to hit the 400 path
64
+ client._post("/v1/check", {"language": "en"})
@@ -0,0 +1,208 @@
1
+ """Native backend selection and wrapper tests (no network, no wheel).
2
+
3
+ The kotoshu_native extension module is not installed in this venv (the
4
+ wheel awaits its first PyPI publish), so import success is simulated with
5
+ a real in-memory module object implementing the documented surface; the
6
+ selection logic itself is exercised through its pure function with plain
7
+ strings and bools.
8
+ """
9
+ import types
10
+
11
+ import pytest
12
+
13
+ import kotoshu
14
+ from kotoshu import Suggestion
15
+ from kotoshu import native as k_native
16
+ from kotoshu.native import Dictionary, NativeBackend, NativeUnavailableError, resolve_backend
17
+
18
+ # The frozen conformance row every backend must agree on.
19
+ HELLO_ROW = {"word": "hello", "distance": 1, "confidence": 1.0, "source": "edit_distance"}
20
+
21
+
22
+ def make_fake_module(*, fail_load=False, fail_ops=False):
23
+ """A real in-memory stand-in for the kotoshu_native extension module."""
24
+ module = types.ModuleType("kotoshu_native")
25
+ module.VERSION = "0.0.0-test"
26
+
27
+ class KotoshuNativeError(Exception):
28
+ pass
29
+
30
+ class Engine:
31
+ def correct(self, word):
32
+ if fail_ops:
33
+ raise KotoshuNativeError("engine boom")
34
+ return word == "hello"
35
+
36
+ def suggest(self, word, limit=5):
37
+ if fail_ops:
38
+ raise KotoshuNativeError("engine boom")
39
+ rows = [HELLO_ROW, {"word": "shells", "distance": 3, "confidence": 0.2, "source": "ngram"}]
40
+ return rows[:limit]
41
+
42
+ def load(aff_path, dic_path):
43
+ if fail_load:
44
+ raise KotoshuNativeError(f"cannot open {aff_path}")
45
+ return Engine()
46
+
47
+ module.KotoshuNativeError = KotoshuNativeError
48
+ module.Dictionary = types.SimpleNamespace(load=load)
49
+ return module
50
+
51
+
52
+ @pytest.fixture
53
+ def no_native(monkeypatch):
54
+ """Simulate the wheel being missing (the failed-import state)."""
55
+ monkeypatch.setattr(k_native, "_native", None)
56
+
57
+
58
+ @pytest.fixture
59
+ def fake_native(monkeypatch):
60
+ """Simulate the wheel being installed."""
61
+ module = make_fake_module()
62
+ monkeypatch.setattr(k_native, "_native", module)
63
+ return module
64
+
65
+
66
+ # ---- Availability ----
67
+
68
+
69
+ def test_available_false_without_wheel(no_native):
70
+ assert k_native.available() is False
71
+ assert NativeBackend.available() is False
72
+
73
+
74
+ def test_available_true_with_module(fake_native):
75
+ assert k_native.available() is True
76
+ assert NativeBackend.available() is True
77
+
78
+
79
+ def test_native_unavailable_error_is_kotoshu_error():
80
+ assert issubclass(NativeUnavailableError, kotoshu.KotoshuError)
81
+
82
+
83
+ # ---- Backend selection (pure decision function) ----
84
+
85
+
86
+ @pytest.mark.parametrize(
87
+ "setting, is_available, expected",
88
+ [
89
+ ("auto", True, "native"),
90
+ ("auto", False, "http"),
91
+ (None, True, "native"),
92
+ (None, False, "http"),
93
+ ("", False, "http"),
94
+ (" Native ", True, "native"),
95
+ ("HTTP", False, "http"),
96
+ ("http", True, "http"),
97
+ ("native", True, "native"),
98
+ ],
99
+ )
100
+ def test_resolve_backend_matrix(setting, is_available, expected):
101
+ assert resolve_backend(setting, is_available) == expected
102
+
103
+
104
+ def test_resolve_backend_forced_native_missing_raises():
105
+ with pytest.raises(NativeUnavailableError) as excinfo:
106
+ resolve_backend("native", False)
107
+ message = str(excinfo.value)
108
+ assert "PyPI" in message
109
+ assert "maturin develop" in message
110
+
111
+
112
+ def test_resolve_backend_invalid_value():
113
+ with pytest.raises(ValueError, match="KOTOSHU_BACKEND"):
114
+ resolve_backend("bogus", True)
115
+
116
+
117
+ # ---- backend() reads the environment ----
118
+
119
+
120
+ def test_backend_auto_falls_back_to_http(no_native, monkeypatch):
121
+ monkeypatch.delenv(k_native.ENV_VAR, raising=False)
122
+ assert kotoshu.backend() == "http"
123
+
124
+
125
+ def test_backend_auto_prefers_native(fake_native, monkeypatch):
126
+ monkeypatch.delenv(k_native.ENV_VAR, raising=False)
127
+ assert kotoshu.backend() == "native"
128
+
129
+
130
+ def test_backend_http_forced(fake_native, monkeypatch):
131
+ monkeypatch.setenv(k_native.ENV_VAR, "http")
132
+ assert kotoshu.backend() == "http"
133
+
134
+
135
+ def test_backend_native_forced_but_unavailable(no_native, monkeypatch):
136
+ monkeypatch.setenv(k_native.ENV_VAR, "native")
137
+ with pytest.raises(NativeUnavailableError) as excinfo:
138
+ kotoshu.backend()
139
+ assert "PyPI" in str(excinfo.value)
140
+ assert "maturin develop" in str(excinfo.value)
141
+
142
+
143
+ def test_backend_invalid_env(fake_native, monkeypatch):
144
+ monkeypatch.setenv(k_native.ENV_VAR, "grpc")
145
+ with pytest.raises(ValueError):
146
+ kotoshu.backend()
147
+
148
+
149
+ # ---- The Dictionary wrapper ----
150
+
151
+
152
+ def test_dictionary_shapes_match_http_client(fake_native):
153
+ d = k_native.dictionary("en_US.aff", "en_US.dic")
154
+ assert isinstance(d, Dictionary)
155
+ assert d.correct("hello") is True
156
+ assert d.correct("hlelo") is False
157
+ assert d.suggest("hlelo", max_suggestions=3) == [
158
+ Suggestion(**HELLO_ROW),
159
+ Suggestion(word="shells", distance=3, confidence=0.2, source="ngram"),
160
+ ]
161
+
162
+
163
+ def test_dictionary_suggest_default_limit(fake_native):
164
+ d = Dictionary.load("en_US.aff", "en_US.dic")
165
+ assert len(d.suggest("hlelo")) == 2
166
+ assert len(d.suggest("hlelo", max_suggestions=1)) == 1
167
+
168
+
169
+ def test_dictionary_version_exposed(fake_native):
170
+ assert NativeBackend().VERSION == "0.0.0-test"
171
+
172
+
173
+ def test_native_backend_unavailable_without_wheel(no_native):
174
+ with pytest.raises(NativeUnavailableError, match="maturin develop"):
175
+ NativeBackend()
176
+ with pytest.raises(NativeUnavailableError, match="maturin develop"):
177
+ k_native.dictionary("en_US.aff", "en_US.dic")
178
+
179
+
180
+ def test_dictionary_load_failure_wrapped(monkeypatch):
181
+ monkeypatch.setattr(k_native, "_native", make_fake_module(fail_load=True))
182
+ with pytest.raises(kotoshu.KotoshuError, match="cannot open") as excinfo:
183
+ k_native.dictionary("bad.aff", "bad.dic")
184
+ assert not isinstance(excinfo.value, NativeUnavailableError)
185
+
186
+
187
+ def test_dictionary_operation_failure_wrapped(monkeypatch):
188
+ monkeypatch.setattr(k_native, "_native", make_fake_module(fail_ops=False))
189
+ d = k_native.dictionary("en_US.aff", "en_US.dic")
190
+ monkeypatch.setattr(k_native, "_native", make_fake_module(fail_ops=True))
191
+ broken = k_native.dictionary("en_US.aff", "en_US.dic")
192
+ with pytest.raises(kotoshu.KotoshuError, match="engine boom"):
193
+ broken.correct("hello")
194
+ with pytest.raises(kotoshu.KotoshuError, match="engine boom"):
195
+ broken.suggest("hlelo")
196
+ assert d.correct("hello") is True
197
+
198
+
199
+ # ---- The real wheel, when it happens to be importable ----
200
+
201
+
202
+ @pytest.mark.skipif(not k_native.available(), reason="kotoshu_native wheel not installed")
203
+ def test_real_module_surface():
204
+ import kotoshu_native
205
+
206
+ assert isinstance(kotoshu_native.VERSION, str)
207
+ assert kotoshu_native.available() is True
208
+ assert NativeBackend().VERSION == kotoshu_native.VERSION