kabosu 0.6.11.4-x86_64-linux → 0.7.0.2-x86_64-linux

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 35471381b6629c0d31472aacae162470842a8156c2391b2b1ccb2861685189e0
4
- data.tar.gz: 5382f364f3eae050ecff3d11eabeb949307d7da5e029cc7e886fd46ea8978dd3
3
+ metadata.gz: ef4af7c2f2b8c87bfdcf4230a70f80dce8e72979c227aa0d1e6be69e472a17e1
4
+ data.tar.gz: 345ffaa4b86884aa5619e5e8cf25e25766c689f232b4508a805a8378fbb7e1ab
5
5
  SHA512:
6
- metadata.gz: 9e3f125d078556fb0333f9e2b7c8ac83a37b71fe1b8666dfd89824b12711cb94c09e70ac75d9cb88d2705390663ab53b9f172532d16222be0035d36cb1bcef4a
7
- data.tar.gz: 95a24438309c088ff6ad2d8fc872e50ec7223486cad81ad4fe3fa09c87d2910899c0697977f7a3a5594da2700c87af8e10ce126549d2a686d834191a38228174
6
+ metadata.gz: 9c3470ac0b230ba241933db8ca9fcb5555f01f917df0a127cbed64e841b5b740506819f55825465f3ca472b4065c6c90c2093f7280a7b7496afdb40f71108b30
7
+ data.tar.gz: b6857d2b5f0d41bfe20e0359ae97a216869dd0268a3bb788bf1dcfa63e8fcccf2e7d68992fef76b5a3ec259ca6a2cf8034d9e637a82ec4eeec68d71b6b46c523
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/README.md CHANGED
@@ -18,40 +18,47 @@ Ruby bindings for [sudachi.rs](https://github.com/WorksApplications/sudachi.rs),
18
18
  ```ruby
19
19
  require "kabosu"
20
20
 
21
- # Explicit dictionary + tokenizer lifecycle
21
+ # A dictionary, and a tokenizer made from it
22
22
  dict = Kabosu::Dictionary.new(system_dict: Kabosu::Dictionary.path)
23
- tokenizer = dict.create(mode: :c)
23
+ tokenizer = dict.tokenizer(mode: :c)
24
24
 
25
25
  # Tokenize Japanese text
26
- morphemes = Kabosu.tokenize("東京都に住んでいる", tokenizer: tokenizer)
26
+ morphemes = tokenizer.tokenize("東京都に住んでいる")
27
27
 
28
28
  # Bulk accessors for quick extraction
29
29
  morphemes.surfaces # => ["東京都", "に", "住ん", "で", "いる"]
30
30
  morphemes.readings # => ["トウキョウト", "ニ", "スン", "デ", "イル"]
31
- morphemes.dictionary_forms # => ["東京都", "に", "住む", "で", "居る"]
31
+ morphemes.dictionary_forms # => ["東京都", "に", "住む", "で", "いる"]
32
+ morphemes.to_s # => "東京都 に 住ん で いる"
32
33
 
33
34
  # Each morpheme exposes rich linguistic detail
34
35
  morpheme = morphemes.first
35
36
  morpheme.surface # => "東京都" - surface form (as it appears in text)
36
- morpheme.part_of_speech # => ["名詞", "固有名詞", "地名", "一般"] — part-of-speech tags
37
- morpheme.part_of_speech_id # => 5 - numeric POS id
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)
38
40
  morpheme.dictionary_form # => "東京都" - base/dictionary form
39
41
  morpheme.normalized_form # => "東京都" - normalized form
40
42
  morpheme.reading_form # => "トウキョウト" - phonetic reading
41
43
  morpheme.oov? # => false - out-of-vocabulary?
42
- morpheme.dictionary_id # => 0 - source dictionary id
43
- morpheme.word_id # => 544373 - internal word id
44
+ morpheme.dictionary_id # => 0 - source dictionary id (-1 for OOV)
45
+ morpheme.word_id # => 7159592 - internal word id
44
46
  morpheme.synonym_group_ids # => [] - synonym group ids
45
- morpheme.dictionary_form_word_id # => -1 - dictionary-form word id
46
- morpheme.head_word_length # => 3 - head word length in codepoints
47
- morpheme.a_unit_split # => [123, 456] - split-A word 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
48
50
  morpheme.b_unit_split # => [] - split-B word ids
49
- morpheme.word_structure # => [123, 456] - word-structure ids
50
- morpheme.total_cost # => 5765 - morphological analysis cost
51
- morpheme.begin # => 0 - start byte offset
52
- morpheme.end # => 9 - end byte offset
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
53
56
  morpheme.begin_c # => 0 - start character offset
54
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)
55
62
  morpheme.system? # => true - from system dictionary?
56
63
  morpheme.user? # => false - from user dictionary?
57
64
 
@@ -60,10 +67,16 @@ Kabosu.split_sentences("東京都に住んでいる。大阪も好きだ。")
60
67
  # => ["東京都に住んでいる。", "大阪も好きだ。"]
61
68
  ```
62
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
+
63
74
  ## Installation
64
75
 
65
76
  - Ruby >= 3.1
66
- - Rust toolchain (for compiling the native extension)
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).
67
80
 
68
81
  Add to your Gemfile:
69
82
 
@@ -75,22 +88,56 @@ Then install and download a [Sudachi dictionary](https://github.com/WorksApplica
75
88
 
76
89
  ```sh
77
90
  bundle install
78
- bundle exec rake kabosu:install[small] # or core, full
91
+ bundle exec rake kabosu:install:small # or :core, :full
79
92
  ```
80
93
 
81
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.
82
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
+
83
130
  ## Dictionary management
84
131
 
85
132
  Rake tasks for managing Sudachi dictionaries:
86
133
 
87
134
  ```sh
88
- rake kabosu:install[small] # Install a dictionary (VERSION=YYYYMMDD for a specific version)
135
+ rake kabosu:install:small # Install a dictionary (VERSION=YYYYMMDD for a specific version)
89
136
  rake kabosu:install_if_missing # Same, but a no-op when a dictionary is already installed
90
137
  rake kabosu:list # List installed dictionaries
91
138
  rake kabosu:versions # Show available versions from GitHub
92
139
  rake kabosu:path # Show path to best available dictionary
93
- rake kabosu:remove[small] # Remove a dictionary (VERSION=YYYYMMDD for a specific version)
140
+ rake kabosu:remove:small # Remove a dictionary (VERSION=YYYYMMDD for a specific version)
94
141
  ```
95
142
 
96
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.
@@ -109,13 +156,47 @@ Sudachi provides three [split modes](https://github.com/WorksApplications/Sudach
109
156
 
110
157
  ```ruby
111
158
  dict = Kabosu::Dictionary.new(system_dict: Kabosu::Dictionary.path)
112
- tok_a = dict.create(mode: :a)
113
- tok_c = dict.create(mode: :c)
159
+ tok_a = dict.tokenizer(mode: :a)
160
+ tok_c = dict.tokenizer(mode: :c)
114
161
  tok_a.tokenize("東京都").surfaces # => ["東京", "都"]
115
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 # => ["東京", "都"]
116
167
  ```
117
168
 
118
- Modes are symbols only (`:a`, `:b`, `:c` or `Kabosu::MODE_A/B/C`).
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.
119
200
 
120
201
  ## Advanced Use Cases
121
202
 
@@ -126,16 +207,31 @@ dict = Kabosu::Dictionary.new(
126
207
  user_dicts: ["/path/to/domain.dic", "/path/to/names.dic"]
127
208
  )
128
209
 
129
- # Create tokenizer with explicit mode/fields
130
- tokenizer = dict.create(mode: :c, fields: %i[surface pos_id reading_form])
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]
131
213
 
132
- # Tokenize (returns MorphemeList; lazily hydrates morphemes)
214
+ # Tokenize: a MorphemeList, which makes Morpheme objects only when asked
133
215
  list = tokenizer.tokenize("国会議事堂前駅")
134
216
  list.surfaces
135
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
136
232
 
137
- # Dictionary prefix lookup
138
- dict.lookup("東京都").surfaces
233
+ # Dictionary prefix lookup (the query is normalized first, like tokenization)
234
+ dict.lookup("東京都").surfaces # => ["東", …, "東京", "東京都"]
139
235
 
140
236
  # Morpheme split
141
237
  m = tokenizer.tokenize("東京都").first
@@ -143,56 +239,85 @@ m.split(mode: :a).surfaces
143
239
 
144
240
  # Sentence splitting
145
241
  Kabosu.split_sentences("東京都に住んでいる。大阪も好きだ。", ranges: true)
146
- Kabosu.split_sentences("長い文...", limit: 12, with_checker: true)
242
+ Kabosu.split_sentences("長い文...", limit: 100) # look at most 100 characters ahead for a boundary
147
243
  ```
148
244
 
149
- ## Benchmarks
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.
150
246
 
151
- Kabosu ships with a benchmark suite that measures tokenization throughput and compares the Ruby bindings against raw [sudachi.rs](https://github.com/WorksApplications/sudachi.rs).
247
+ Paths may be Strings or Pathnames. `Dictionary#create` is the older name of `#tokenizer` and still works.
152
248
 
153
- This benchmark uses [Wagahai wa Neko de Aru](https://www.aozora.gr.jp/cards/000148/card789.html) (I Am a Cat) by Natsume Soseki, sourced from [Aozora Bunko](https://www.aozora.gr.jp/) (public domain) as the source text. ~958 KB of Japanese prose, 2,256 lines as input.
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`.
154
250
 
155
- ### Results
251
+ ### Parts of speech
156
252
 
157
- Measured on an AMD Ryzen 7 5800X, `full` dictionary edition, Ruby 3.4, Rust 1.84:
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
+ ```
158
277
 
159
- Single-thread (10 iterations):
278
+ ### Dictionary entries and forms (sudachi.rs 0.7)
160
279
 
161
- | Scenario | Rust | Ruby | Ratio |
162
- |---|---|---|---|
163
- | split_sentences | 1.550s | 1.615s | 1.0x |
164
- | tokenize (mode C) | 3.148s | 3.395s | 1.1x |
165
- | tokenize (mode A) | 3.227s | 3.525s | 1.1x |
166
- | tokenize (mode B) | 3.226s | 3.582s | 1.1x |
167
- | **Throughput** | **2.94 MB/s** | **2.69 MB/s** | **1.1x** |
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.
168
285
 
169
- Multithread (8 threads x 20,000 requests):
286
+ # Every entry in the loaded dictionaries, lazily (millions for `full`)
287
+ dict.entries.lazy.select(&:user?).first(10)
170
288
 
171
- | Scenario | Rust | Ruby | Ratio |
172
- |---|---|---|---|
173
- | rails-style shared tokenizer | 1.475s | 2.101s | 1.4x |
174
- | tokenizer per thread | 1.381s | 2.154s | 1.6x |
175
- | **Throughput ST** | **20.44 MB/s** | **14.35 MB/s** | **1.4x** |
176
- | **Throughput PT** | **21.84 MB/s** | **14.00 MB/s** | **1.6x** |
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 # => ["カボス"]
177
292
 
178
- Notes:
179
- - `shared tokenizer` matches Rails-style access where all request threads call one tokenizer instance.
180
- - `per thread` creates one tokenizer per worker thread.
181
- - Ratios are `Ruby / Rust`, and values vary by CPU, Ruby version, and dictionary edition.
293
+ # Hand-made out-of-vocabulary morpheme; forms default to the surface
294
+ dict.oov_morpheme(m.part_of_speech_id, "ズィーガン", reading: "ジーガン")
182
295
 
183
- To reproduce these results, run:
296
+ # What tokenization actually sees after the input-text plugins
297
+ dict.normalize("カボス ABC コンピュータ〜〜") # => "カボス abc コンピューター"
184
298
 
185
- ```sh
186
- bundle exec ruby bench/start
299
+ # Compile a user dictionary against the installed system dictionary
300
+ Kabosu.build_user_dict("names.csv", output: "names.dic")
187
301
  ```
188
302
 
189
- To generate flamegraph SVGs alongside the benchmark:
303
+ ## Benchmarks
190
304
 
191
- ```sh
192
- bundle exec ruby bench/start --profile
193
- ```
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.
194
319
 
195
- This records both the Rust and Ruby runs with `perf` and produces interactive SVGs (`bench/flamegraph-rust.svg`, `bench/flamegraph-ruby.svg`). Open them in a browser to explore.
320
+ Methodology, the full tables and how to reproduce are in [bench/README.md](bench/README.md).
196
321
 
197
322
  ## Contributing
198
323
 
@@ -204,5 +329,5 @@ bundle exec rake kabosu:install # Install Sudachi dictionary
204
329
  bundle exec rake compile # Build the native extension
205
330
  bundle exec rake test # Run tests
206
331
 
207
- bench/start # Run benchmarks
332
+ bench/run # Run benchmarks
208
333
  ```
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -10,9 +10,16 @@ module Kabosu
10
10
  EDITION_PRIORITY = %w[full core small].freeze
11
11
  GITHUB_REPO = "WorksApplications/SudachiDict".freeze
12
12
  GITHUB_API = "https://api.github.com".freeze
13
+ # sudachi.rs 0.7 reads only V1 dictionaries, which open with this magic.
14
+ # Older (V0) files stay listed so they can be removed, but are never picked.
15
+ V1_MAGIC = "SudachiBinaryDic".b.freeze
16
+ # The first SudachiDict GitHub release carrying V1 assets. v20260723.1 is
17
+ # V1 too, but was published to PyPI only and has no assets to download.
18
+ MIN_VERSION = "20261015".freeze
13
19
 
14
20
  class DictNotFound < StandardError; end
15
21
  class DownloadError < StandardError; end
22
+ class UnsupportedVersion < StandardError; end
16
23
 
17
24
  # Default storage directory. Honors KABOSU_DICT_DIR so consumers can point
18
25
  # the gem at a Docker volume / shared mount without subclassing or threading
@@ -37,13 +44,19 @@ module Kabosu
37
44
  def install(edition = "core", version: nil)
38
45
  edition = validate_edition(edition)
39
46
  version ||= latest_version
47
+ validate_version(version)
40
48
 
41
49
  dest_dir = File.join(@dir, "sudachi-dictionary-#{version}")
42
50
  dic_path = File.join(dest_dir, "system_#{edition}.dic")
43
51
 
44
52
  if File.exist?(dic_path)
45
- warn "Already installed: #{dic_path}"
46
- return dic_path
53
+ if v1?(dic_path)
54
+ warn "Already installed: #{dic_path}"
55
+ return dic_path
56
+ end
57
+
58
+ warn "Replacing pre-V1 dictionary: #{dic_path}"
59
+ FileUtils.rm_f(dic_path)
47
60
  end
48
61
 
49
62
  FileUtils.mkdir_p(@dir)
@@ -73,6 +86,11 @@ module Kabosu
73
86
 
74
87
  raise DownloadError, "Expected #{dic_path} after extraction, but file not found" unless File.exist?(dic_path)
75
88
 
89
+ unless v1?(dic_path)
90
+ FileUtils.rm_f(dic_path)
91
+ raise UnsupportedVersion, "#{version}/#{edition} is not a V1 dictionary, which sudachi.rs 0.7+ requires"
92
+ end
93
+
76
94
  warn "Installed: #{dic_path}"
77
95
  dic_path
78
96
  end
@@ -87,7 +105,7 @@ module Kabosu
87
105
  #
88
106
  def install_if_missing(edition = "core", version: nil)
89
107
  edition = validate_edition(edition)
90
- matching = installed.find do |d|
108
+ matching = readable.find do |d|
91
109
  d[:edition] == edition && (version.nil? || d[:version] == version)
92
110
  end
93
111
  return matching[:path] if matching
@@ -121,8 +139,13 @@ module Kabosu
121
139
  # Find the best available dictionary path.
122
140
  # Prefers: latest version, then full > core > small.
123
141
  def find(edition: nil)
124
- candidates = installed
125
- raise DictNotFound, "No dictionaries installed. Run: rake kabosu:install" if candidates.empty?
142
+ candidates = readable
143
+ if candidates.empty?
144
+ raise DictNotFound, "No dictionaries installed. Run: rake kabosu:install" if installed.empty?
145
+
146
+ raise DictNotFound, "Only pre-V1 dictionaries are installed, which sudachi.rs 0.7+ cannot read. " \
147
+ "Run: rake kabosu:install (and rake kabosu:remove VERSION=... for the old ones)"
148
+ end
126
149
 
127
150
  if edition
128
151
  edition = validate_edition(edition)
@@ -144,6 +167,14 @@ module Kabosu
144
167
  best.is_a?(Hash) ? best[:path] : latest_version_dicts.first[:path]
145
168
  end
146
169
 
170
+ def readable
171
+ installed.select { |d| v1?(d[:path]) }
172
+ end
173
+
174
+ def v1?(path)
175
+ File.binread(path, V1_MAGIC.bytesize) == V1_MAGIC
176
+ end
177
+
147
178
  # ── Remove ──
148
179
 
149
180
  # Remove a specific dictionary edition, or an entire version.
@@ -189,6 +220,15 @@ module Kabosu
189
220
 
190
221
  private
191
222
 
223
+ def validate_version(version)
224
+ return if Gem::Version.new(version) >= Gem::Version.new(MIN_VERSION)
225
+
226
+ raise UnsupportedVersion, "SudachiDict #{version} predates the V1 format sudachi.rs 0.7+ reads; " \
227
+ "use #{MIN_VERSION} or later"
228
+ rescue ArgumentError
229
+ raise UnsupportedVersion, "Malformed SudachiDict version: #{version.inspect}"
230
+ end
231
+
192
232
  def validate_edition(edition)
193
233
  edition = edition.to_s.downcase
194
234
  unless EDITIONS.include?(edition)