kabosu 0.6.11.4-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.
data/lib/kabosu.rb CHANGED
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require_relative "kabosu/version"
2
4
 
3
5
  # Load the native extension. Precompiled gems place it under a per-Ruby-version
@@ -16,13 +18,25 @@ require_relative "kabosu/pos_matcher"
16
18
  require_relative "kabosu/morpheme_list"
17
19
  require_relative "kabosu/railtie" if defined?(Rails::Railtie)
18
20
 
21
+ # The native extension defines the classes below and the native halves of
22
+ # their methods (named with a leading underscore, private). This file adds the
23
+ # public, keyword-argument API on top.
24
+ #
25
+ # The error classes are defined natively too, so the extension raises them
26
+ # directly (ext/kabosu/src/errors.rs):
27
+ #
28
+ # Kabosu::Error < StandardError anything else that goes wrong natively
29
+ # Kabosu::ConfigError a config file is missing, unreadable or invalid
30
+ # Kabosu::DictionaryError a dictionary cannot be loaded, read or built
31
+ # Kabosu::LookupError Dictionary#lookup / #lookup_all_entries failed
32
+ # Kabosu::TokenizationError Tokenizer#tokenize / Morpheme#split failed
33
+ # Kabosu::SentenceSplitError Kabosu.split_sentences failed
19
34
  module Kabosu
20
- class Error < StandardError; end
21
- class ConfigError < Error; end
22
- class DictionaryError < Error; end
23
- class LookupError < Error; end
24
- class TokenizationError < Error; end
25
- class SentenceSplitError < Error; end
35
+ MODE_A = :a
36
+ MODE_B = :b
37
+ MODE_C = :c
38
+
39
+ private_constant :NativeMorphemeList
26
40
 
27
41
  class SentenceRange
28
42
  attr_reader :start, :end, :text
@@ -38,55 +52,60 @@ module Kabosu
38
52
  end
39
53
  end
40
54
 
41
- remove_const(:MODE_A) if const_defined?(:MODE_A, false)
42
- remove_const(:MODE_B) if const_defined?(:MODE_B, false)
43
- remove_const(:MODE_C) if const_defined?(:MODE_C, false)
44
- MODE_A = :a
45
- MODE_B = :b
46
- MODE_C = :c
47
- private_constant :TokenBatch if const_defined?(:TokenBatch, false)
48
-
49
- def self.normalize_mode(mode, param_name: "mode")
50
- case mode
51
- when :a
52
- "A"
53
- when :b
54
- "B"
55
- when :c
56
- "C"
57
- else
58
- raise ArgumentError, "invalid #{param_name} #{mode.inspect}; expected :a, :b, or :c"
55
+ # Argument checks shared by the public entry points.
56
+ module Arguments
57
+ module_function
58
+
59
+ # A filesystem path from a String or anything with #to_path (Pathname).
60
+ def path(value, name)
61
+ File.path(value)
62
+ rescue TypeError
63
+ raise ArgumentError, "#{name} must be a String or Pathname, got #{value.class}"
59
64
  end
60
- end
61
- private_class_method :normalize_mode
62
65
 
63
- # ── Dictionary: keyword API and management ──
66
+ def optional_path(value, name)
67
+ value.nil? ? nil : path(value, name)
68
+ end
69
+
70
+ def string(value, name)
71
+ raise ArgumentError, "#{name} must be a String, got #{value.class}" unless value.is_a?(String)
72
+
73
+ value
74
+ end
75
+
76
+ def boolean(value, name)
77
+ raise ArgumentError, "#{name} must be true or false" unless [true, false].include?(value)
78
+
79
+ value
80
+ end
81
+ end
82
+ private_constant :Arguments
64
83
 
65
84
  class Dictionary
66
85
  DEFAULT_CONFIG_PATH = File.expand_path("kabosu/resources/sudachi.json", __dir__).freeze
67
86
 
68
87
  class << self
69
- alias _new new
70
-
88
+ # Loads a dictionary. Give the system dictionary explicitly, or a config
89
+ # file that names one; paths may be Strings or Pathnames.
90
+ #
91
+ # Kabosu::Dictionary.new(system_dict: Kabosu::Dictionary.path)
92
+ # Kabosu::Dictionary.new(system_dict: path, user_dicts: ["names.dic"])
93
+ # Kabosu::Dictionary.new(config: "sudachi.json")
71
94
  def new(config: nil, system_dict: nil, user_dicts: nil)
72
- raise ArgumentError, "config must be a String or nil" unless config.nil? || config.is_a?(String)
73
- raise ArgumentError, "system_dict must be a String or nil" unless system_dict.nil? || system_dict.is_a?(String)
95
+ config = Arguments.optional_path(config, "config")
96
+ system_dict = Arguments.optional_path(system_dict, "system_dict")
74
97
  unless user_dicts.nil? || user_dicts.is_a?(Array)
75
- raise ArgumentError, "user_dicts must be an Array<String> or nil"
98
+ raise ArgumentError, "user_dicts must be an Array of paths or nil"
76
99
  end
77
- raise ArgumentError, "user_dicts must contain only String values" if user_dicts&.any? { !_1.is_a?(String) }
78
-
79
100
  raise ArgumentError, "either config or system_dict is required" if config.nil? && system_dict.nil?
80
101
 
102
+ user_dicts = user_dicts&.map { Arguments.path(_1, "user_dicts") }
103
+
81
104
  # Default to the sudachi.json bundled with this gem when only
82
105
  # system_dict is given. sudachi.rs's own default config path is
83
106
  # captured via env!("CARGO_MANIFEST_DIR") and doesn't exist on
84
107
  # consumers' machines once the gem is precompiled and shipped.
85
- config ||= DEFAULT_CONFIG_PATH
86
-
87
- _new(config, system_dict, user_dicts)
88
- rescue RuntimeError => e
89
- raise map_dictionary_init_error(e, config: config, system_dict: system_dict)
108
+ _new(config || DEFAULT_CONFIG_PATH, system_dict, user_dicts)
90
109
  end
91
110
 
92
111
  def install(edition = "core", version: nil)
@@ -101,122 +120,212 @@ module Kabosu
101
120
  dict_manager.installed
102
121
  end
103
122
 
104
- private
123
+ private :_new
105
124
 
106
- def map_dictionary_init_error(error, config:, system_dict:)
107
- message = error.message
108
- if (config && system_dict.nil?) || message.match?(/config|setting\.json|json/i)
109
- ConfigError.new(message)
110
- else
111
- DictionaryError.new(message)
112
- end
113
- end
125
+ private
114
126
 
115
127
  def dict_manager
116
128
  @dict_manager ||= DictManager.new
117
129
  end
118
130
  end
119
131
 
120
- alias _create create
121
- alias _lookup lookup
132
+ # Creates a tokenizer. One tokenizer can be shared by any number of
133
+ # threads.
134
+ #
135
+ # mode:: :a, :b or :c (default), the unit the text is split into.
136
+ # fields:: the word-info fields to load, e.g. %i[surface pos_id]; nil
137
+ # loads all of them. Accessors for fields that were left out
138
+ # return empty values, and Morpheme#split needs split_a/split_b.
139
+ # debug:: have sudachi.rs print the lattice while tokenizing.
140
+ def tokenizer(mode: MODE_C, fields: nil, debug: false, projection: nil)
141
+ Arguments.boolean(debug, "debug")
142
+ raise NotImplementedError, "projection is not supported yet" unless projection.nil?
122
143
 
123
- def create(**options)
124
- unknown = options.keys - %i[mode fields debug projection]
125
- raise ArgumentError, "unknown keyword(s): #{unknown.join(", ")}" unless unknown.empty?
144
+ fields = fields.to_a if fields.is_a?(Enumerable)
145
+ _tokenizer(mode, fields, debug)
146
+ end
147
+ # The name this method had before SudachiPy renamed it. Not deprecated.
148
+ alias create tokenizer
126
149
 
127
- mode = options.fetch(:mode, MODE_C)
128
- fields = options.fetch(:fields, nil)
129
- debug = options.fetch(:debug, false)
130
- projection = options.fetch(:projection, nil)
150
+ # Every dictionary entry that is a prefix of text, as a MorphemeList over
151
+ # text. The query is normalized first, as tokenization does.
152
+ def lookup(text)
153
+ MorphemeList.new(_lookup(Arguments.string(text, "text")))
154
+ end
131
155
 
132
- raise ArgumentError, "fields must be an Array<String|Symbol> or nil" unless fields.nil? || fields.is_a?(Array)
133
- if fields&.any? { !(_1.is_a?(String) || _1.is_a?(Symbol)) }
134
- raise ArgumentError, "fields must contain only String or Symbol values"
135
- end
136
- raise ArgumentError, "debug must be true or false" unless [true, false].include?(debug)
156
+ # Every public dictionary entry as a standalone Morpheme (offsets cover its
157
+ # own headword). Lazy: a `full` dictionary holds millions of entries, so
158
+ # chain with `.lazy`, `.first(n)` or `.each` rather than `.to_a`.
159
+ #
160
+ # dict.entries.lazy.select { _1.user? }.first(10)
161
+ def entries(&block)
162
+ return enum_for(:entries) unless block
137
163
 
138
- raise NotImplementedError, "projection is not supported yet" unless projection.nil?
164
+ _each_entry(&block)
165
+ self
166
+ end
139
167
 
140
- mode_str = Kabosu.__send__(:normalize_mode, mode)
141
- _create(mode_str, fields, debug)
168
+ # Like #lookup, but exact matches only and found by scanning every entry,
169
+ # so it also finds entries that are not indexed for lookup. Slow; other
170
+ # threads keep running during the scan.
171
+ def lookup_all_entries(surface)
172
+ MorphemeList.new(_lookup_all_entries(Arguments.string(surface, "surface")))
142
173
  end
143
174
 
144
- def lookup(text)
145
- raise ArgumentError, "text must be a String" unless text.is_a?(String)
175
+ # Builds an out-of-vocabulary Morpheme by hand. The forms default to the
176
+ # surface. pos_id comes from Morpheme#part_of_speech_id.
177
+ #
178
+ # dict.oov_morpheme(pos_id, "ズィーガンボルト", reading: "ズィーガンボルト")
179
+ def oov_morpheme(pos_id, surface, reading: nil, normalized_form: nil, dictionary_form: nil)
180
+ raise ArgumentError, "pos_id must be an Integer" unless pos_id.is_a?(Integer)
181
+ raise ArgumentError, "invalid part-of-speech id #{pos_id}" unless pos_id.between?(0, 0xFFFF)
146
182
 
147
- MorphemeList.new(_lookup(text))
148
- rescue RuntimeError => e
149
- raise LookupError.new(e.message), cause: e
183
+ _oov_morpheme(pos_id, Arguments.string(surface, "surface"), reading, normalized_form, dictionary_form)
150
184
  end
151
- end
152
185
 
153
- # ── Tokenizer: wrap output in MorphemeList ──
186
+ # A PosMatcher that knows this dictionary's parts of speech, so matching a
187
+ # morpheme from it is a table lookup rather than a string comparison.
188
+ #
189
+ # nouns = dict.pos_matcher(["名詞"])
190
+ # dict.pos_matcher(["名詞", "固有名詞"], ["動詞"])
191
+ # dict.pos_matcher { |pos| pos[5] == "終止形-一般" }
192
+ #
193
+ # A pattern that matches no part of speech in this dictionary is most
194
+ # likely a typo, and raises ArgumentError.
195
+ def pos_matcher(*patterns, &)
196
+ # Also accept SudachiPy's shape: one list of patterns.
197
+ first = patterns.first
198
+ patterns = first if patterns.size == 1 && first.is_a?(Array) && !first.empty? && first.all?(Array)
199
+
200
+ patterns.each do |pattern|
201
+ next unless PosMatcher.new(pattern, dictionary: self).empty?
202
+
203
+ raise ArgumentError, "POS pattern #{pattern.inspect} does not match any part of speech in this dictionary"
204
+ end
205
+ PosMatcher.new(*patterns, dictionary: self, &)
206
+ end
154
207
 
155
- class Tokenizer
156
- alias _tokenize tokenize
208
+ private :_tokenizer, :_lookup, :_each_entry, :_lookup_all_entries, :_oov_morpheme
209
+ end
157
210
 
211
+ class Tokenizer
212
+ # Tokenizes text into a MorphemeList. Raises TokenizationError for input
213
+ # over sudachi.rs's limit of 49,149 bytes; split longer text first, e.g.
214
+ # with Kabosu.split_sentences.
158
215
  def tokenize(text)
159
- raise ArgumentError, "text must be a String" unless text.is_a?(String)
216
+ MorphemeList.new(_tokenize(Arguments.string(text, "text")))
217
+ end
160
218
 
161
- batch = _tokenize(text)
162
- cost = batch.respond_to?(:internal_cost) ? batch.internal_cost : nil
163
- MorphemeList.new(batch, internal_cost: cost)
164
- rescue RuntimeError => e
165
- raise TokenizationError.new(e.message), cause: e
219
+ # Tokenizes each text of an Array, returning one MorphemeList per text.
220
+ #
221
+ # The same as `texts.map { tokenize(_1) }`, but the GVL is released once
222
+ # per 64 KB of text rather than once per text. With several threads
223
+ # tokenizing short texts, that hand-off is what they spend their time
224
+ # waiting for, so batching sentences is noticeably faster there. Every
225
+ # text is checked before any is analyzed: one bad text fails the batch.
226
+ def tokenize_batch(texts)
227
+ raise ArgumentError, "texts must be an Array of Strings" unless texts.is_a?(Array) && texts.all?(String)
228
+
229
+ _tokenize_batch(texts).map! { MorphemeList.new(_1) }
166
230
  end
231
+
232
+ private :_tokenize, :_tokenize_batch
167
233
  end
168
234
 
169
235
  class Morpheme
170
- alias _split split
236
+ # The sub-units of this morpheme in a finer split mode, as a MorphemeList.
237
+ #
238
+ # A morpheme with no finer split gives an empty list, as in SudachiPy. Pass
239
+ # add_single: true to get a list holding the morpheme itself instead, so
240
+ # that `list.flat_map { _1.split(mode: :a, add_single: true).to_a }` is the
241
+ # mode-A tokenization.
242
+ def split(mode:, add_single: false)
243
+ MorphemeList.new(_split(mode, Arguments.boolean(add_single, "add_single")))
244
+ end
171
245
 
172
- def split(mode: MODE_C, add_single: true)
173
- raise ArgumentError, "add_single must be true or false" unless [true, false].include?(add_single)
246
+ # Where this morpheme sits in the tokenized text, in characters:
247
+ # `text[m.char_range] == m.surface`.
248
+ def char_range
249
+ begin_c...end_c
250
+ end
174
251
 
175
- mode_str = Kabosu.__send__(:normalize_mode, mode)
176
- MorphemeList.new(_split(mode_str, nil, add_single))
177
- rescue RuntimeError => e
178
- raise TokenizationError.new(e.message), cause: e
252
+ # The same in bytes: `text.byteslice(m.byte_range) == m.surface`.
253
+ # #begin and #end are byte offsets too.
254
+ def byte_range
255
+ self.begin...self.end
179
256
  end
180
- end
181
257
 
182
- def self.split_sentences(text, limit: nil, with_checker: false, ranges: false, dictionary: nil)
183
- raise ArgumentError, "text must be a String" unless text.is_a?(String)
184
- raise ArgumentError, "limit must be an Integer or nil" unless limit.nil? || limit.is_a?(Integer)
185
- raise ArgumentError, "limit must be greater than 0" if limit && limit < 1
186
- raise ArgumentError, "with_checker must be true or false" unless [true, false].include?(with_checker)
187
- raise ArgumentError, "ranges must be true or false" unless [true, false].include?(ranges)
188
- raise ArgumentError, "dictionary must be a String path or nil" unless dictionary.nil? || dictionary.is_a?(String)
258
+ alias size length
189
259
 
190
- dict_path = nil
191
- dict_path = dictionary || Dictionary.path if with_checker
260
+ FIELDS = %i[surface part_of_speech part_of_speech_id dictionary_form normalized_form reading_form
261
+ begin_c end_c begin end oov? dictionary_id word_id synonym_group_ids user_data].freeze
192
262
 
193
- if ranges
194
- _split_sentences_with_ranges(text, limit, dict_path).map do |(start, finish, sentence)|
195
- SentenceRange.new(start, finish, sentence)
263
+ # The morpheme as a Hash, keyed by reader name (`oov?` is `:oov`).
264
+ def to_h
265
+ deconstruct_keys(nil)
266
+ end
267
+
268
+ # For pattern matching:
269
+ #
270
+ # case morpheme
271
+ # in { part_of_speech: ["名詞", *], surface: } then …
272
+ # end
273
+ def deconstruct_keys(keys)
274
+ (keys ? FIELDS.select { keys.include?(_1.to_s.delete_suffix("?").to_sym) } : FIELDS).to_h do |reader|
275
+ [reader.to_s.delete_suffix("?").to_sym, public_send(reader)]
196
276
  end
197
- else
198
- _split_sentences(text, limit, dict_path)
199
277
  end
200
- rescue RuntimeError => e
201
- raise SentenceSplitError.new(e.message), cause: e
278
+
279
+ private :_split
202
280
  end
203
281
 
204
- # ── Convenience tokenization ──
205
-
206
- # Tokenize text using an explicitly provided tokenizer.
207
- #
208
- # dict = Kabosu::Dictionary.new(system_dict: Kabosu::Dictionary.path)
209
- # tok = dict.create(mode: :a)
210
- # Kabosu.tokenize("東京都に住んでいる", tokenizer: tok)
211
- #
212
- def self.tokenize(text, tokenizer:)
213
- raise ArgumentError, "text must be a String" unless text.is_a?(String)
214
- raise ArgumentError, "tokenizer must be a Kabosu::Tokenizer" unless tokenizer.is_a?(Tokenizer)
215
-
216
- batch = tokenizer.__send__(:_tokenize, text)
217
- cost = batch.respond_to?(:internal_cost) ? batch.internal_cost : nil
218
- MorphemeList.new(batch, internal_cost: cost)
219
- rescue RuntimeError => e
220
- raise TokenizationError.new(e.message), cause: e
282
+ class << self
283
+ # Compiles user-dictionary CSV(s) into a binary user dictionary. The result
284
+ # loads only next to the system dictionary it was built against, so rebuild
285
+ # whenever that changes (including the move to sudachi.rs 0.7).
286
+ #
287
+ # Kabosu.build_user_dict("names.csv", output: "names.dic")
288
+ # Kabosu::Dictionary.new(system_dict: Kabosu::Dictionary.path, user_dicts: ["names.dic"])
289
+ def build_user_dict(inputs, output:, system_dict: Dictionary.path, description: nil)
290
+ inputs = Array(inputs).map { Arguments.path(_1, "inputs") }
291
+ output = Arguments.path(output, "output")
292
+
293
+ _build_user_dict(inputs, Arguments.path(system_dict, "system_dict"), output, description)
294
+ output
295
+ end
296
+
297
+ # Splits text into sentences.
298
+ #
299
+ # limit:: how many characters ahead to look for the end of a
300
+ # sentence (default 4096). When there is none that close,
301
+ # the rest of the text is returned as one sentence.
302
+ # ranges:: return SentenceRange objects (byte offsets plus text).
303
+ # with_checker:: consult a dictionary so that a boundary does not fall
304
+ # inside a word (the 。 of モーニング娘。). Known bug in
305
+ # sudachi.rs 0.7.0: this also suppresses every boundary
306
+ # whose punctuation mark is a dictionary word, as 。 is,
307
+ # unless it ends the text. In practice most text comes back
308
+ # unsplit; leave the checker off until sudachi.rs ships the
309
+ # fix (its PR #369).
310
+ # dictionary:: that dictionary: a Kabosu::Dictionary, which is reused, or
311
+ # the path of a system dictionary, which is loaded on every
312
+ # call (default: Dictionary.path). Implies with_checker.
313
+ def split_sentences(text, limit: nil, with_checker: false, ranges: false, dictionary: nil)
314
+ Arguments.string(text, "text")
315
+ raise ArgumentError, "limit must be an Integer or nil" unless limit.nil? || limit.is_a?(Integer)
316
+ raise ArgumentError, "limit must be greater than 0" if limit && limit < 1
317
+
318
+ # No text is this long, and anything larger does not fit a native integer.
319
+ limit = [limit, 0xFFFF_FFFF].min if limit
320
+
321
+ Arguments.boolean(ranges, "ranges")
322
+ dictionary = Arguments.path(dictionary, "dictionary") unless dictionary.nil? || dictionary.is_a?(Dictionary)
323
+ checker = dictionary || (Dictionary.path if Arguments.boolean(with_checker, "with_checker"))
324
+
325
+ sentences = _split_sentences(text, limit, checker, ranges)
326
+ ranges ? sentences.map! { |start, finish, sentence| SentenceRange.new(start, finish, sentence) } : sentences
327
+ end
328
+
329
+ private :_build_user_dict, :_split_sentences
221
330
  end
222
331
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: kabosu
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.6.11.4
4
+ version: 0.7.0.2
5
5
  platform: aarch64-linux
6
6
  authors:
7
7
  - davafons
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-09-13 00:00:00.000000000 Z
11
+ date: 2026-12-05 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: rubyzip
@@ -42,16 +42,22 @@ dependencies:
42
42
  name: minitest
43
43
  requirement: !ruby/object:Gem::Requirement
44
44
  requirements:
45
- - - "~>"
45
+ - - ">="
46
46
  - !ruby/object:Gem::Version
47
47
  version: '5.0'
48
+ - - "<"
49
+ - !ruby/object:Gem::Version
50
+ version: '7'
48
51
  type: :development
49
52
  prerelease: false
50
53
  version_requirements: !ruby/object:Gem::Requirement
51
54
  requirements:
52
- - - "~>"
55
+ - - ">="
53
56
  - !ruby/object:Gem::Version
54
57
  version: '5.0'
58
+ - - "<"
59
+ - !ruby/object:Gem::Version
60
+ version: '7'
55
61
  - !ruby/object:Gem::Dependency
56
62
  name: rake
57
63
  requirement: !ruby/object:Gem::Requirement
@@ -101,6 +107,7 @@ executables: []
101
107
  extensions: []
102
108
  extra_rdoc_files: []
103
109
  files:
110
+ - CHANGELOG.md
104
111
  - LICENSE
105
112
  - README.md
106
113
  - lib/kabosu.rb