kabosu 0.7.0.2-x64-mingw-ucrt

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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: b7d48cd4c714a82be683f59dda9943be43c7705ce5fd20d193527797f67b0de4
4
+ data.tar.gz: 6f039b314af1a0d6eaf8b81f53cb4df4d721418e7096f60fcffc63d4f161b59f
5
+ SHA512:
6
+ metadata.gz: a94b060570af82ec2181f03fdc7e0c2fc865da98970581e6fded7dff809c64b29918e853a6bdb22485e1bae2948c69778a039008eb319d0b266e8eff695512fe
7
+ data.tar.gz: f37cdc5cfe7a874e51c8a84bd0d2b88c76727ad72f697877d73fc54c34ec487078f636dba50b0059817862c7d60b179464e24a767f931706f81c0da5622d7969
data/CHANGELOG.md ADDED
@@ -0,0 +1,118 @@
1
+ # Changelog
2
+
3
+ Versions follow sudachi.rs: `0.7.0.x` wraps sudachi.rs `0.7.0`.
4
+
5
+ ## 0.7.0.2 (2026-12-05)
6
+
7
+ A rework of the native binding. Tokenization output is unchanged (it is still
8
+ checked field by field against raw sudachi.rs and against SudachiPy), but a few
9
+ return types and edge-case behaviours are different: see **Changed**.
10
+
11
+ ### Fixed
12
+
13
+ - **Tokenizers and dictionaries were never freed.** Each tokenizer left its
14
+ analyzer, and through it the whole dictionary, in a thread-local cache that
15
+ was never cleaned up: 5,000 short-lived tokenizers grew a process by 2.4 GB.
16
+ Analyzers now live in a pool owned by the `Tokenizer` and go away with it.
17
+ - **`part_of_speech` could return another dictionary's part of speech.** The
18
+ cache behind it was keyed by the dictionary's memory address, so a dictionary
19
+ allocated where a collected one had lived inherited its entries. Each
20
+ dictionary now owns one frozen table, indexed by POS id.
21
+ - **Errors were classified by pattern-matching their message**, which turned a
22
+ missing dictionary under `~/.config/` into a `ConfigError` and
23
+ `Ractor::UnsafeError` into a `DictionaryError`. The extension now raises the
24
+ right `Kabosu::*Error` itself. Integers too large for native code
25
+ (`pos_of(10**30)`) no longer raise `RangeError`.
26
+ - **An exception delivered during a call leaked what the call was using.**
27
+ `Timeout`, `Thread#raise` and `Thread#kill` arriving while the GVL was
28
+ released jumped out of the native code without running its cleanup. Calls
29
+ now finish their cleanup first and re-raise afterwards.
30
+ - Input over the 49,149-byte limit is refused before it is copied; a failed
31
+ call with a very large String used to leave a copy of it in the tokenizer.
32
+ - `Dictionary#lookup` took time quadratic in the length of the query (4 s for
33
+ 16,000 characters); it is a single pass now.
34
+ - `Morpheme#inspect` did not escape quotes.
35
+
36
+ ### Known issues
37
+
38
+ - `Kabosu.split_sentences` with `with_checker: true` or `dictionary:` hardly
39
+ splits at all. The checker of sudachi.rs 0.7.0 suppresses every boundary
40
+ whose punctuation mark is a dictionary word (。 is one) unless it ends the
41
+ text. Fixed upstream by sudachi.rs PR #369, not yet released; kabosu stays
42
+ on 0.7.0, so leave the checker off. The tests for it are skipped until then.
43
+
44
+ ### Changed
45
+
46
+ - `Tokenizer#mode` returns a Symbol (`:a`, `:b`, `:c`), the same value
47
+ `tokenizer(mode:)` takes, instead of `"A"`/`"B"`/`"C"`. Modes are also
48
+ accepted as Strings, in either case.
49
+ - `Tokenizer#fields` returns Symbols instead of Strings, one name per field,
50
+ and every name it returns is accepted back by `fields:`. `synonym_group_ids`
51
+ is reported under that name (it was `synonym_group_id`), and
52
+ `dictionary_form_word_id` is no longer listed next to `dictionary_form`
53
+ (both still select the same field).
54
+ - The Strings in `MorphemeList#surfaces` are frozen, like every other String
55
+ kabosu returns for a morpheme.
56
+ - Every String a morpheme returns is frozen. `surface` and `dictionary_form`
57
+ already were; `reading_form`, `normalized_form`, `user_data` and `to_s` now
58
+ are too. Use `+m.reading_form` or `.dup` for a mutable copy.
59
+ - With a `fields:` subset, the word-info accessors (`a_unit_split`,
60
+ `b_unit_split`, `c_unit_split`, `word_structure`, `synonym_group_ids`,
61
+ `dictionary_form_word_id`) and `Morpheme#split` use only the fields that were
62
+ loaded, as SudachiPy does; they used to read the full entry regardless. A
63
+ tokenizer created without `fields:` is not affected.
64
+ - The parts returned by `Morpheme#split` report sudachi.rs's own `total_cost`
65
+ for split nodes (`2147483647`, the same value a mode-A or mode-B tokenization
66
+ reports) instead of a copy of the parent's cost.
67
+ - `Morpheme#split` defaults to `add_single: false`, as SudachiPy does: a
68
+ morpheme with no finer split gives an empty list instead of a list holding
69
+ itself. `mode:` is now required.
70
+ - `Kabosu.tokenize(text, tokenizer:)` is removed; it only called
71
+ `tokenizer.tokenize(text)`.
72
+ - `Tokenizer#internal_cost` is gone: it was the cost of whichever thread's call
73
+ finished last. Use `MorphemeList#internal_cost` on the result. That reader no
74
+ longer has a writer, and is `nil` for lists that are not a tokenization.
75
+ - `MorphemeList#to_s` is the surfaces joined by spaces (as SudachiPy prints a
76
+ list) instead of Ruby's default `#<Kabosu::MorphemeList…>`; `#each` returns
77
+ the list.
78
+ - The native halves of the public methods (`Dictionary._new`, `#_create`,
79
+ `Tokenizer#_tokenize`, `Morpheme#_split`, …) are private, and the internal
80
+ `Kabosu::TokenBatch` class is gone.
81
+
82
+ ### Added
83
+
84
+ - `Dictionary#tokenizer`, SudachiPy's name for `#create` (which stays).
85
+ - `Dictionary#pos_of(id)` and `Dictionary#pos_list`.
86
+ - `Dictionary#pos_matcher`: a `PosMatcher` bound to the dictionary, which
87
+ decides each part of speech once and then matches morphemes by table lookup.
88
+ `PosMatcher` gains `~`/`invert`, `bind`, `ids`, `size`, `each`/`to_a`, and
89
+ works as a block (`select(&matcher)`) and in `case`/`grep`.
90
+ - `Tokenizer#tokenize_batch(texts)`: tokenizes an Array of texts with the GVL
91
+ released once per 64 KB of text instead of once per text. With 8 threads on short sentences this scaled
92
+ 5.5x where one `tokenize` call per sentence scaled 3.0x (local measurement).
93
+ - `MorphemeList#readings`, `#dictionary_forms`, `#normalized_forms`,
94
+ `#total_costs` and the new `#parts_of_speech` are read natively in one call,
95
+ like `#surfaces`, without making Morpheme objects.
96
+ - `Kabosu.split_sentences(dictionary:)` accepts a `Kabosu::Dictionary`, which
97
+ is reused, as well as a path, which is loaded on every call.
98
+ - `Morpheme#to_h` and `#deconstruct_keys` (pattern matching).
99
+ - `Morpheme#==`, `#eql?` and `#hash` compare by value: the same word of the
100
+ same dictionary with the same surface and offsets, whichever object it was
101
+ read through.
102
+ - A tokenizer keeps separate analyzers for inputs over 4 KB, so one large
103
+ document no longer slows down every short sentence tokenized after it.
104
+ - `Kabosu.build_user_dict` releases the GVL while it builds.
105
+ - `Morpheme#length`/`#size` (in characters), `#raw_surface`, `#char_range` and
106
+ `#byte_range`.
107
+ - `MorphemeList#length`, `#[start, length]`, `#[range]`, `#slice`.
108
+ - A precompiled `x64-mingw-ucrt` (Windows) gem is cross-built for release. It
109
+ compiles and links; the test suite has not been run on Windows yet (CI has
110
+ an experimental, non-blocking job for it).
111
+ - Paths may be Pathnames (anything with `#to_path`).
112
+ - `fields:` accepts a Set, Strings in either case, and SudachiPy's `pos`.
113
+ - `Dictionary#lookup_all_entries` releases the GVL during its scan.
114
+ - Native memory is reported to Ruby's GC and to `ObjectSpace.memsize_of`. An
115
+ analyzer is reported by the longest input it has seen (about 11 MB after a
116
+ 45 KB document).
117
+ - Documented: thread safety, `fork`, the 49,149-byte input limit, and that
118
+ Ractors are refused (`Ractor::UnsafeError`).
data/LICENSE ADDED
@@ -0,0 +1,191 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to the Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by the Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding any notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ Copyright 2025 davafons
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,333 @@
1
+ <p align="center">
2
+ <img src="logo.png" alt="Kabosu" width="150">
3
+ </p>
4
+
5
+ <h1 align="center">Kabosu</h1>
6
+
7
+ <p align="center">
8
+ <a href="https://rubygems.org/gems/kabosu"><img src="https://img.shields.io/gem/v/kabosu" alt="Gem Version"></a>
9
+ <a href="https://github.com/davafons/kabosu/actions/workflows/edge.yml"><img src="https://github.com/davafons/kabosu/actions/workflows/edge.yml/badge.svg" alt="CI"></a>
10
+ <a href="https://github.com/davafons/kabosu/blob/main/LICENSE"><img src="https://img.shields.io/github/license/davafons/kabosu" alt="License"></a>
11
+ <a href="https://rubygems.org/gems/kabosu"><img src="https://img.shields.io/gem/dt/kabosu" alt="Downloads"></a>
12
+ </p>
13
+
14
+ Ruby bindings for [sudachi.rs](https://github.com/WorksApplications/sudachi.rs), a Rust implementation of the [Sudachi](https://github.com/WorksApplications/Sudachi) Japanese morphological analyzer.
15
+
16
+ ## Usage
17
+
18
+ ```ruby
19
+ require "kabosu"
20
+
21
+ # A dictionary, and a tokenizer made from it
22
+ dict = Kabosu::Dictionary.new(system_dict: Kabosu::Dictionary.path)
23
+ tokenizer = dict.tokenizer(mode: :c)
24
+
25
+ # Tokenize Japanese text
26
+ morphemes = tokenizer.tokenize("東京都に住んでいる")
27
+
28
+ # Bulk accessors for quick extraction
29
+ morphemes.surfaces # => ["東京都", "に", "住ん", "で", "いる"]
30
+ morphemes.readings # => ["トウキョウト", "ニ", "スン", "デ", "イル"]
31
+ morphemes.dictionary_forms # => ["東京都", "に", "住む", "で", "いる"]
32
+ morphemes.to_s # => "東京都 に 住ん で いる"
33
+
34
+ # Each morpheme exposes rich linguistic detail
35
+ morpheme = morphemes.first
36
+ morpheme.surface # => "東京都" - surface form (as it appears in text)
37
+ morpheme.part_of_speech # => ["名詞", "固有名詞", "地名", "一般", "*", "*"]
38
+ # - four POS levels, conjugation type, conjugation form
39
+ morpheme.part_of_speech_id # => 1349 - numeric POS id (see Dictionary#pos_of)
40
+ morpheme.dictionary_form # => "東京都" - base/dictionary form
41
+ morpheme.normalized_form # => "東京都" - normalized form
42
+ morpheme.reading_form # => "トウキョウト" - phonetic reading
43
+ morpheme.oov? # => false - out-of-vocabulary?
44
+ morpheme.dictionary_id # => 0 - source dictionary id (-1 for OOV)
45
+ morpheme.word_id # => 7159592 - internal word id
46
+ morpheme.synonym_group_ids # => [] - synonym group ids
47
+ morpheme.dictionary_form_word_id # => -1 - dictionary-form word id (-1: the word itself)
48
+ morpheme.head_word_length # => 9 - bytes of the normalized index form
49
+ morpheme.a_unit_split # => [2290714, 3237156] - split-A word ids
50
+ morpheme.b_unit_split # => [] - split-B word ids
51
+ morpheme.word_structure # => [2290714, 3237156] - word-structure ids
52
+ morpheme.c_unit_split # => [] - split-C word ids (V1 dictionaries)
53
+ morpheme.user_data # => "" - free text from a user dictionary's user_data column
54
+ morpheme.total_cost # => 5221 - cumulative lattice path cost
55
+ morpheme.length # => 3 - length in characters
56
+ morpheme.begin_c # => 0 - start character offset
57
+ morpheme.end_c # => 3 - end character offset
58
+ morpheme.char_range # => 0...3 - text[m.char_range] == m.surface
59
+ morpheme.begin # => 0 - start BYTE offset
60
+ morpheme.end # => 9 - end BYTE offset
61
+ morpheme.byte_range # => 0...9 - text.byteslice(m.byte_range) == m.surface (UTF-8 text)
62
+ morpheme.system? # => true - from system dictionary?
63
+ morpheme.user? # => false - from user dictionary?
64
+
65
+ # Split text into natural Japanese sentence boundaries
66
+ Kabosu.split_sentences("東京都に住んでいる。大阪も好きだ。")
67
+ # => ["東京都に住んでいる。", "大阪も好きだ。"]
68
+ ```
69
+
70
+ [CHANGELOG.md](CHANGELOG.md) lists what changed between releases, and [test/parity/PARITY.md](test/parity/PARITY.md) compares kabosu with SudachiPy, the official Python binding.
71
+
72
+ `begin`/`end` are byte offsets; use `begin_c`/`end_c`/`char_range` to index into a Ruby String. Every String a morpheme returns is frozen (`+m.surface` gives a mutable copy), and `part_of_speech` is a frozen Array shared by all morphemes with that part of speech.
73
+
74
+ ## Installation
75
+
76
+ - Ruby >= 3.1
77
+ - No Rust is needed where a precompiled gem exists: Linux (`x86_64-linux`, `aarch64-linux`, and their `-musl` variants) and macOS (`arm64-darwin`, `x86_64-darwin`).
78
+ - Windows (`x64-mingw-ucrt`) is experimental: the precompiled gem is published only when its smoke test passes, and it has never been tested on a real Windows machine.
79
+ - Any other platform builds the extension from source on install, which needs a Rust toolchain and network access (sudachi.rs is fetched from GitHub).
80
+
81
+ Add to your Gemfile:
82
+
83
+ ```ruby
84
+ gem "kabosu"
85
+ ```
86
+
87
+ Then install and download a [Sudachi dictionary](https://github.com/WorksApplications/SudachiDict):
88
+
89
+ ```sh
90
+ bundle install
91
+ bundle exec rake kabosu:install:small # or :core, :full
92
+ ```
93
+
94
+ Dictionary editions (from smallest to largest): `small`, `core`, `full`. See the [SudachiDict documentation](https://github.com/WorksApplications/SudachiDict?tab=readme-ov-file#dictionary-types) for details on the differences between editions.
95
+
96
+ kabosu 0.7 (sudachi.rs 0.7) reads only the V1 dictionary format: SudachiDict `20261015` or later.
97
+
98
+ ## Upgrading from 0.6
99
+
100
+ sudachi.rs 0.7 changed the binary dictionary format, so a 0.6 setup needs three things:
101
+
102
+ 1. **Reinstall the system dictionary.** Dictionaries installed by kabosu 0.6 are V0 and cannot be loaded. Run `rake kabosu:install` (or `install_if_missing`, which ignores V0 files), then drop the old ones with `rake kabosu:remove VERSION=...`. `rake kabosu:list` marks them.
103
+ 2. **Rebuild user dictionaries** against that exact system dictionary: `rake kabosu:build_user_dict CSV=names.csv OUTPUT=names.dic` (or `Kabosu.build_user_dict`). A user dictionary now records which system dictionary it was built with, and loading it with a different one raises `Kabosu::DictionaryError`. The CSV uses the V1 column layout (see [Sudachi's user dictionary guide](https://github.com/WorksApplications/Sudachi/blob/develop/docs/user_dict.md)).
104
+ 3. **Expect small tokenization differences.** sudachi.rs 0.7 aligned its lattice search, character-category handling and katakana OOV joining with Java Sudachi, so some inputs segment differently even with the same dictionary. Custom `char.def` files must replace `NOOOVBOW2` with `NOOOVBOW NOOOVEOW`.
105
+
106
+ Other visible changes: `Dictionary#lookup` normalizes the query first (`カボス` finds カボス), joined numerals and katakana carry an OOV `word_id` instead of `4294967295`, and a custom config that names no `char.def`/`unk.def` falls back to the files built into sudachi.rs.
107
+
108
+ ## Upgrading to 0.7.0.2
109
+
110
+ The fourth version number is kabosu's own; this release reworks the binding and changes some of its API. Tokenization output is the same. Details and the list of fixes are in [CHANGELOG.md](CHANGELOG.md).
111
+
112
+ | Before | Now |
113
+ |---|---|
114
+ | `Tokenizer#mode # => "C"` | `# => :c`, the value `tokenizer(mode:)` takes. Strings (`"C"`, `"c"`) are accepted as input. |
115
+ | `Tokenizer#fields # => ["surface", …]` | Symbols, one name per field; `synonym_group_id` is now `synonym_group_ids`, and `dictionary_form_word_id` is no longer listed. |
116
+ | `m.split(mode: :a)` returned `[m]` when there was nothing to split | Returns an empty list (SudachiPy's default). Pass `add_single: true` for the old behaviour. `mode:` is now required. |
117
+ | `Kabosu.tokenize(text, tokenizer: tok)` | Removed. Use `tok.tokenize(text)`. |
118
+ | `Tokenizer#internal_cost` | Removed (it was the last call from any thread). Use `tok.tokenize(text).internal_cost`. |
119
+ | `list.internal_cost = n` | Removed; it is read-only, and `nil` for lists that are not a tokenization. |
120
+ | `m.reading_form`, `normalized_form`, `user_data`, `to_s` returned mutable Strings | Frozen, like `surface` and `dictionary_form`. Use `+m.reading_form` for a mutable copy. |
121
+ | With `fields:`, `a_unit_split`, `word_structure`, `synonym_group_ids`, `split` … read the full entry anyway | They use only the fields that were loaded. No change without `fields:`. |
122
+ | Parts of `m.split` had the parent's `total_cost` | They have sudachi.rs's value for split nodes, `2147483647`. |
123
+ | `list.surfaces` returned mutable Strings | Frozen too. |
124
+ | `list.to_s # => "#<Kabosu::MorphemeList…>"` | The surfaces joined by spaces; `inspect` is unchanged. |
125
+ | `Dictionary._new`, `#_create`, `Tokenizer#_tokenize`, `Kabosu::TokenBatch` | Private or gone; they were never public API. |
126
+ | Errors re-raised from `RuntimeError` with a `cause` | Raised directly as the right `Kabosu::*Error`; a dictionary passed as `system_dict:` or `user_dicts:` that cannot be loaded is always `DictionaryError`, whatever its path looks like; one named by the config file is `ConfigError`. |
127
+
128
+ `Dictionary#create` still works; `#tokenizer` is the preferred name.
129
+
130
+ ## Dictionary management
131
+
132
+ Rake tasks for managing Sudachi dictionaries:
133
+
134
+ ```sh
135
+ rake kabosu:install:small # Install a dictionary (VERSION=YYYYMMDD for a specific version)
136
+ rake kabosu:install_if_missing # Same, but a no-op when a dictionary is already installed
137
+ rake kabosu:list # List installed dictionaries
138
+ rake kabosu:versions # Show available versions from GitHub
139
+ rake kabosu:path # Show path to best available dictionary
140
+ rake kabosu:remove:small # Remove a dictionary (VERSION=YYYYMMDD for a specific version)
141
+ ```
142
+
143
+ Dictionaries are stored in `~/.kabosu/dict/` by default. Set `KABOSU_DICT_DIR` to customize — useful for pointing at a Docker volume so the dictionary persists across deployments.
144
+
145
+ In a Rails app, the rake tasks are auto-loaded via railtie — no manual `load` needed. For container entrypoints, `rake kabosu:install_if_missing` converges on the desired state without hitting the network on subsequent runs.
146
+
147
+ ## Tokenization modes
148
+
149
+ Sudachi provides three [split modes](https://github.com/WorksApplications/Sudachi?tab=readme-ov-file#the-modes-of-splitting):
150
+
151
+ | Mode | Description |
152
+ |------|-------------|
153
+ | `A` | Short units (most granular) |
154
+ | `B` | Middle units |
155
+ | `C` | Named entity units (default) |
156
+
157
+ ```ruby
158
+ dict = Kabosu::Dictionary.new(system_dict: Kabosu::Dictionary.path)
159
+ tok_a = dict.tokenizer(mode: :a)
160
+ tok_c = dict.tokenizer(mode: :c)
161
+ tok_a.tokenize("東京都").surfaces # => ["東京", "都"]
162
+ tok_c.tokenize("東京都").surfaces # => ["東京都"]
163
+ tok_a.mode # => :a
164
+
165
+ # A mode-C morpheme can be split further afterwards
166
+ tok_c.tokenize("東京都").first.split(mode: :a).surfaces # => ["東京", "都"]
167
+ ```
168
+
169
+ A mode is `:a`, `:b` or `:c` (also `Kabosu::MODE_A/B/C`, or a String in either case); `Tokenizer#mode` returns the Symbol.
170
+
171
+ `Morpheme#split` returns an empty list for a morpheme with no finer split, as SudachiPy does. Pass `add_single: true` to get the morpheme itself instead: `list.flat_map { _1.split(mode: :a, add_single: true).to_a }` is the mode-A tokenization.
172
+
173
+ ## Input limits and errors
174
+
175
+ sudachi.rs indexes its input with 16-bit offsets, so one `tokenize` call takes at most **49,149 bytes** of UTF-8 (about 16,000 kana or kanji). Longer input raises `Kabosu::TokenizationError`; split it first, for example with `Kabosu.split_sentences`. The same limit applies to `Dictionary#lookup` and `#normalize`.
176
+
177
+ Text must be valid UTF-8 (or another encoding Ruby can transcode to it). Invalid bytes and binary Strings raise `EncodingError`. Text in another encoding is analyzed as its UTF-8 transcription, and byte offsets (`begin`, `end`, `byte_range`) count bytes of that transcription, not of the String you passed: slice `text.encode("UTF-8")` with them, or use the character offsets (`begin_c`, `end_c`, `char_range`), which are the same in any encoding.
178
+
179
+ | Error | Raised when |
180
+ |---|---|
181
+ | `Kabosu::ConfigError` | a config file is missing, unreadable or invalid, or names a dictionary that cannot be loaded |
182
+ | `Kabosu::DictionaryError` | a dictionary passed as `system_dict:` or `user_dicts:` cannot be loaded; a dictionary cannot be read or built |
183
+ | `Kabosu::TokenizationError` | `Tokenizer#tokenize` or `Morpheme#split` fails |
184
+ | `Kabosu::LookupError` | `Dictionary#lookup` or `#lookup_all_entries` fails |
185
+ | `Kabosu::SentenceSplitError` | `Kabosu.split_sentences` fails |
186
+ | `Kabosu::Error` | superclass of the above, and anything else native |
187
+
188
+ Bad arguments raise `ArgumentError`.
189
+
190
+ ## Threads, processes and Ractors
191
+
192
+ - **Threads.** A `Dictionary` and a `Tokenizer` can be shared by any number of threads; create them once (for example at boot) and reuse them. `tokenize` releases the GVL while it analyzes, so threads tokenize in parallel, each on its own analyzer drawn from a small pool the tokenizer owns. `Dictionary#lookup_all_entries` and `Kabosu.split_sentences` release it too.
193
+ - **Many short texts from several threads.** Use `tokenizer.tokenize_batch(texts)`: it returns one `MorphemeList` per text but releases the GVL once per 64 KB of text instead of once per text. Handing the GVL back and forth after every sentence is what threads otherwise spend their time waiting for.
194
+ - **Timeouts and interrupts.** `Timeout`, `Thread#raise`, `Thread#kill` and signals are delivered when a call next takes the GVL back: after the text being analyzed (at most 49,149 bytes, a few milliseconds), or after the current 64 KB of a batch. The tokenizer stays usable and nothing is leaked. `Kabosu.build_user_dict` and `Dictionary#lookup_all_entries` run to the end first, which can take seconds.
195
+ - **Results.** A `MorphemeList` and its morphemes are ordinary Ruby objects: readable from any thread, and valid for as long as you hold them, even after the tokenizer and dictionary that made them are gone.
196
+ - **fork.** Objects created before a `fork` keep working in the child, and the dictionary's memory-mapped pages stay shared, so preloading in a forking server is cheap.
197
+ - **Ractors are not supported.** The extension is not marked Ractor-safe: calling it from a non-main Ractor raises `Ractor::UnsafeError`, and its objects can be neither shared with nor copied into a Ractor. Use threads.
198
+
199
+ Native memory is released when the Ruby object that owns it is garbage-collected, and is reported to the GC so that short-lived tokenizers and results do not pile up unseen.
200
+
201
+ ## Advanced Use Cases
202
+
203
+ ```ruby
204
+ # Custom system dictionary + optional user dictionaries
205
+ dict = Kabosu::Dictionary.new(
206
+ system_dict: "/path/to/custom/system.dic",
207
+ user_dicts: ["/path/to/domain.dic", "/path/to/names.dic"]
208
+ )
209
+
210
+ # Load only some word-info fields (faster); the others read as empty
211
+ tokenizer = dict.tokenizer(mode: :c, fields: %i[surface pos_id reading_form])
212
+ tokenizer.fields # => [:surface, :pos_id, :reading_form]
213
+
214
+ # Tokenize: a MorphemeList, which makes Morpheme objects only when asked
215
+ list = tokenizer.tokenize("国会議事堂前駅")
216
+ list.surfaces
217
+ list.first.part_of_speech
218
+ list.size
219
+ list[0] # one Morpheme
220
+ list[0, 2] # an Array of Morphemes, as are list[1..] and list.first(2)
221
+ list.internal_cost
222
+
223
+ # Whole-list readers: one native call each, no Morpheme objects made
224
+ list.surfaces; list.readings; list.dictionary_forms; list.normalized_forms
225
+ list.parts_of_speech; list.total_costs
226
+
227
+ # Pattern matching and Hashes
228
+ case list.first
229
+ in { part_of_speech: ["名詞", *], surface: } then surface
230
+ end
231
+ list.first.to_h
232
+
233
+ # Dictionary prefix lookup (the query is normalized first, like tokenization)
234
+ dict.lookup("東京都").surfaces # => ["東", …, "東京", "東京都"]
235
+
236
+ # Morpheme split
237
+ m = tokenizer.tokenize("東京都").first
238
+ m.split(mode: :a).surfaces
239
+
240
+ # Sentence splitting
241
+ Kabosu.split_sentences("東京都に住んでいる。大阪も好きだ。", ranges: true)
242
+ Kabosu.split_sentences("長い文...", limit: 100) # look at most 100 characters ahead for a boundary
243
+ ```
244
+
245
+ `Kabosu.split_sentences` also takes `with_checker: true` or `dictionary: dict`, which consult a dictionary so that a boundary does not fall inside a word such as モーニング娘。. **In sudachi.rs 0.7.0 this is broken**: the checker also suppresses every boundary whose punctuation mark is itself a dictionary word, as 。 is, so most text comes back as one sentence. It is fixed upstream (sudachi.rs PR #369) but not released; leave the checker off until kabosu moves to that release.
246
+
247
+ Paths may be Strings or Pathnames. `Dictionary#create` is the older name of `#tokenizer` and still works.
248
+
249
+ The fields are `surface`, `pos_id`, `normalized_form`, `dictionary_form`, `reading_form`, `head_word_length`, `split_a`, `split_b`, `split_c`, `word_structure`, `synonym_group_ids` and `user_data`, as Symbols or Strings (SudachiPy's `pos` is accepted too). `Morpheme#split` needs `split_a`/`split_b`.
250
+
251
+ ### Parts of speech
252
+
253
+ ```ruby
254
+ # A matcher made by the dictionary decides every part of speech it has up
255
+ # front, so matching one of its morphemes is a table lookup.
256
+ nouns = dict.pos_matcher(["名詞"])
257
+ names = dict.pos_matcher(["名詞", "固有名詞"]) # trailing levels are wildcards
258
+ finite = dict.pos_matcher { |pos| pos[5] == "終止形-一般" }
259
+
260
+ list = tokenizer.tokenize("東京都に住んでいる")
261
+ list.select_pos(nouns).surfaces # => ["東京都"]
262
+ list.reject_pos(nouns | finite).surfaces
263
+ nouns.match?(list.first) # => true
264
+ list.select(&nouns) # works as a block, and in `case`/`grep`
265
+
266
+ (nouns - names).size # set operations: |, &, -, ~
267
+ (~nouns).to_a # the matching parts of speech
268
+ nouns.ids # and their ids
269
+
270
+ dict.pos_of(1349) # => ["名詞", "固有名詞", "地名", "一般", "*", "*"]
271
+ dict.pos_list.size # every part of speech, indexed by id
272
+
273
+ # Without a dictionary: compares strings, works on any object with #part_of_speech
274
+ Kabosu::PosMatcher.nouns
275
+ Kabosu::PosMatcher.new(["動詞"], ["形容詞"])
276
+ ```
277
+
278
+ ### Dictionary entries and forms (sudachi.rs 0.7)
279
+
280
+ ```ruby
281
+ m = tokenizer.tokenize("住んでいた").first # 住ん
282
+ m.dictionary_form_morpheme # the 住む entry itself: POS, reading, ids…
283
+ tokenizer.tokenize("附属").first.normalized_form_morpheme.surface # => "付属"
284
+ # A word that is its own form (and any OOV word of a tokenization) returns itself.
285
+
286
+ # Every entry in the loaded dictionaries, lazily (millions for `full`)
287
+ dict.entries.lazy.select(&:user?).first(10)
288
+
289
+ # Exact matches by scanning every entry, including ones not indexed for
290
+ # lookup. Slow on large dictionaries; prefer #lookup.
291
+ dict.lookup_all_entries("カボス").surfaces # => ["カボス"]
292
+
293
+ # Hand-made out-of-vocabulary morpheme; forms default to the surface
294
+ dict.oov_morpheme(m.part_of_speech_id, "ズィーガン", reading: "ジーガン")
295
+
296
+ # What tokenization actually sees after the input-text plugins
297
+ dict.normalize("カボス ABC コンピュータ〜〜") # => "カボス abc コンピューター"
298
+
299
+ # Compile a user dictionary against the installed system dictionary
300
+ Kabosu.build_user_dict("names.csv", output: "names.dic")
301
+ ```
302
+
303
+ ## Benchmarks
304
+
305
+ Kabosu is benchmarked against [SudachiPy](https://github.com/WorksApplications/sudachi.rs/tree/develop/python) (the official Python binding) and raw [sudachi.rs](https://github.com/WorksApplications/sudachi.rs), all three on the same dictionary file, config and corpus ([Wagahai wa Neko de Aru](https://www.aozora.gr.jp/cards/000148/card789.html), Aozora Bunko, public domain).
306
+
307
+ One pass over 6,428 sentences (207k morphemes), split mode C, single thread, median of 15 passes:
308
+
309
+ | Workload | sudachi.rs (Rust) | SudachiPy | kabosu | kabosu + YJIT |
310
+ |---|---:|---:|---:|---:|
311
+ | tokenize only | 263 ms | 264 ms | 290 ms | 286 ms |
312
+ | + `surface` of every morpheme | 264 ms | 306 ms | 348 ms | 328 ms |
313
+ | + 5 fields of every morpheme | 302 ms | 411 ms | 445 ms | 410 ms |
314
+
315
+ - Memory: 221 MB RSS at steady state with the core dictionary (SudachiPy 201 MB, Rust 184 MB); creating 5,000 tokenizers or reloading the dictionary 20 times leaves RSS flat.
316
+ - Threads: tokenize-only throughput on 8 threads is 4.4x one thread with a shared tokenizer, 5.0x with `tokenize_batch` (SudachiPy 6.7x with a tokenizer per thread).
317
+
318
+ Measured on an AMD Ryzen 7 5800X, Linux x86_64, Ruby 4.0.2, CPython 3.14.8 with SudachiPy 0.7.0, Rust 1.95.0, sudachi.rs 0.7.0, SudachiDict core 20261015. Rust reads fields as borrowed strings and builds no objects, so it is a floor rather than a peer. SudachiPy's Linux wheel is built with profile-guided optimization; kabosu is not.
319
+
320
+ Methodology, the full tables and how to reproduce are in [bench/README.md](bench/README.md).
321
+
322
+ ## Contributing
323
+
324
+ ```sh
325
+ bundle install
326
+
327
+ bundle exec rake kabosu:install # Install Sudachi dictionary
328
+
329
+ bundle exec rake compile # Build the native extension
330
+ bundle exec rake test # Run tests
331
+
332
+ bench/run # Run benchmarks
333
+ ```
Binary file
Binary file
Binary file