kabosu 0.7.0.1-aarch64-linux → 0.7.0.2-aarch64-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: ba6c61184a10e59d12f7618f0769f27766422c11644ec5c47af51f7eb1775890
4
- data.tar.gz: 1442e054d02e0bbfaad77d0447f32f33b00d8dec19aafd4c9f60062b0b1e11d4
3
+ metadata.gz: 3c06c6f8e7741ed9525944ab092cb9e806756af6be84854bbb4c3362ce9f8d52
4
+ data.tar.gz: 06e4fc5d5725d5241633dc4407e574728275b7b3fefef585e7cfba097053c81e
5
5
  SHA512:
6
- metadata.gz: cc59f91c5486eebb6382f68df24459d6dc34aa52c02e53197d6538c5e19830c9865a6c859535d2e95d8f082ea5beb928e0106ed6c5b7afd3a7a66220cbc847c1
7
- data.tar.gz: f187ffa82f345736a0a160b4146ed6c9b6b7f4c69bfa98a03a76d80075c6670554a76063cffb3ba724d38bd3b237fdf8871a8c540eee81aa70b7168d2dfdfc46
6
+ metadata.gz: 9c7091c30536448815f41a4913eb2031ae86be701c44a1a3f32a98ca37675d2fa19d5d8d439e910ba62adbdb8dbaba5b2d047e1586b513f3392218e13e174e97
7
+ data.tar.gz: 1f8bb87db696e36d8b4c97cb564b79f775fe06f16799aa9761a3cefead37de905a0d8fb868e5ec8fd52e77d91318720706158fdf5d4b80beb355bff906ebb0f6
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,42 +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
47
+ morpheme.dictionary_form_word_id # => -1 - dictionary-form word id (-1: the word itself)
46
48
  morpheme.head_word_length # => 9 - bytes of the normalized index form
47
- morpheme.a_unit_split # => [123, 456] - split-A word ids
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
51
+ morpheme.word_structure # => [2290714, 3237156] - word-structure ids
50
52
  morpheme.c_unit_split # => [] - split-C word ids (V1 dictionaries)
51
53
  morpheme.user_data # => "" - free text from a user dictionary's user_data column
52
- morpheme.total_cost # => 5765 - morphological analysis cost
53
- morpheme.begin # => 0 - start byte offset
54
- morpheme.end # => 9 - end byte offset
54
+ morpheme.total_cost # => 5221 - cumulative lattice path cost
55
+ morpheme.length # => 3 - length in characters
55
56
  morpheme.begin_c # => 0 - start character offset
56
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)
57
62
  morpheme.system? # => true - from system dictionary?
58
63
  morpheme.user? # => false - from user dictionary?
59
64
 
@@ -62,10 +67,16 @@ Kabosu.split_sentences("東京都に住んでいる。大阪も好きだ。")
62
67
  # => ["東京都に住んでいる。", "大阪も好きだ。"]
63
68
  ```
64
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
+
65
74
  ## Installation
66
75
 
67
76
  - Ruby >= 3.1
68
- - 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).
69
80
 
70
81
  Add to your Gemfile:
71
82
 
@@ -94,6 +105,28 @@ sudachi.rs 0.7 changed the binary dictionary format, so a 0.6 setup needs three
94
105
 
95
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.
96
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
+
97
130
  ## Dictionary management
98
131
 
99
132
  Rake tasks for managing Sudachi dictionaries:
@@ -123,13 +156,47 @@ Sudachi provides three [split modes](https://github.com/WorksApplications/Sudach
123
156
 
124
157
  ```ruby
125
158
  dict = Kabosu::Dictionary.new(system_dict: Kabosu::Dictionary.path)
126
- tok_a = dict.create(mode: :a)
127
- tok_c = dict.create(mode: :c)
159
+ tok_a = dict.tokenizer(mode: :a)
160
+ tok_c = dict.tokenizer(mode: :c)
128
161
  tok_a.tokenize("東京都").surfaces # => ["東京", "都"]
129
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 # => ["東京", "都"]
130
167
  ```
131
168
 
132
- 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.
133
200
 
134
201
  ## Advanced Use Cases
135
202
 
@@ -140,16 +207,31 @@ dict = Kabosu::Dictionary.new(
140
207
  user_dicts: ["/path/to/domain.dic", "/path/to/names.dic"]
141
208
  )
142
209
 
143
- # Create tokenizer with explicit mode/fields
144
- 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]
145
213
 
146
- # Tokenize (returns MorphemeList; lazily hydrates morphemes)
214
+ # Tokenize: a MorphemeList, which makes Morpheme objects only when asked
147
215
  list = tokenizer.tokenize("国会議事堂前駅")
148
216
  list.surfaces
149
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
150
232
 
151
233
  # Dictionary prefix lookup (the query is normalized first, like tokenization)
152
- dict.lookup("東京都").surfaces
234
+ dict.lookup("東京都").surfaces # => ["東", …, "東京", "東京都"]
153
235
 
154
236
  # Morpheme split
155
237
  m = tokenizer.tokenize("東京都").first
@@ -157,7 +239,40 @@ m.split(mode: :a).surfaces
157
239
 
158
240
  # Sentence splitting
159
241
  Kabosu.split_sentences("東京都に住んでいる。大阪も好きだ。", ranges: true)
160
- Kabosu.split_sentences("長い文...", limit: 12, with_checker: 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(["動詞"], ["形容詞"])
161
276
  ```
162
277
 
163
278
  ### Dictionary entries and forms (sudachi.rs 0.7)
@@ -166,7 +281,7 @@ Kabosu.split_sentences("長い文...", limit: 12, with_checker: true)
166
281
  m = tokenizer.tokenize("住んでいた").first # 住ん
167
282
  m.dictionary_form_morpheme # the 住む entry itself: POS, reading, ids…
168
283
  tokenizer.tokenize("附属").first.normalized_form_morpheme.surface # => "付属"
169
- # A word that is its own form (and any OOV word) returns itself.
284
+ # A word that is its own form (and any OOV word of a tokenization) returns itself.
170
285
 
171
286
  # Every entry in the loaded dictionaries, lazily (millions for `full`)
172
287
  dict.entries.lazy.select(&:user?).first(10)
@@ -187,51 +302,22 @@ Kabosu.build_user_dict("names.csv", output: "names.dic")
187
302
 
188
303
  ## Benchmarks
189
304
 
190
- 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).
191
-
192
- 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.
193
-
194
- ### Results
195
-
196
- Measured on an AMD Ryzen 7 5800X, `full` dictionary edition, Ruby 3.4, Rust 1.84:
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).
197
306
 
198
- Single-thread (10 iterations):
307
+ One pass over 6,428 sentences (207k morphemes), split mode C, single thread, median of 15 passes:
199
308
 
200
- | Scenario | Rust | Ruby | Ratio |
201
- |---|---|---|---|
202
- | split_sentences | 1.550s | 1.615s | 1.0x |
203
- | tokenize (mode C) | 3.148s | 3.395s | 1.1x |
204
- | tokenize (mode A) | 3.227s | 3.525s | 1.1x |
205
- | tokenize (mode B) | 3.226s | 3.582s | 1.1x |
206
- | **Throughput** | **2.94 MB/s** | **2.69 MB/s** | **1.1x** |
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 |
207
314
 
208
- Multithread (8 threads x 20,000 requests):
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).
209
317
 
210
- | Scenario | Rust | Ruby | Ratio |
211
- |---|---|---|---|
212
- | rails-style shared tokenizer | 1.475s | 2.101s | 1.4x |
213
- | tokenizer per thread | 1.381s | 2.154s | 1.6x |
214
- | **Throughput ST** | **20.44 MB/s** | **14.35 MB/s** | **1.4x** |
215
- | **Throughput PT** | **21.84 MB/s** | **14.00 MB/s** | **1.6x** |
216
-
217
- Notes:
218
- - `shared tokenizer` matches Rails-style access where all request threads call one tokenizer instance.
219
- - `per thread` creates one tokenizer per worker thread.
220
- - Ratios are `Ruby / Rust`, and values vary by CPU, Ruby version, and dictionary edition.
221
-
222
- To reproduce these results, run:
223
-
224
- ```sh
225
- bundle exec ruby bench/start
226
- ```
227
-
228
- To generate flamegraph SVGs alongside the benchmark:
229
-
230
- ```sh
231
- bundle exec ruby bench/start --profile
232
- ```
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.
233
319
 
234
- 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).
235
321
 
236
322
  ## Contributing
237
323
 
@@ -243,5 +329,5 @@ bundle exec rake kabosu:install # Install Sudachi dictionary
243
329
  bundle exec rake compile # Build the native extension
244
330
  bundle exec rake test # Run tests
245
331
 
246
- bench/start # Run benchmarks
332
+ bench/run # Run benchmarks
247
333
  ```
Binary file
Binary file
Binary file
Binary file
Binary file