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.
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,60 +120,37 @@ module Kabosu
101
120
  dict_manager.installed
102
121
  end
103
122
 
104
- private
105
-
106
- def map_dictionary_init_error(error, config:, system_dict:)
107
- message = error.message
108
- if message.include?("V0 version")
109
- return DictionaryError.new(
110
- "#{message}: a system or user dictionary is in the pre-V1 format, which sudachi.rs 0.7+ cannot read. " \
111
- "Install SudachiDict #{DictManager::MIN_VERSION} or later (rake kabosu:install) " \
112
- "and rebuild user dictionaries against it."
113
- )
114
- end
123
+ private :_new
115
124
 
116
- if (config && system_dict.nil?) || message.match?(/config|setting\.json|json/i)
117
- ConfigError.new(message)
118
- else
119
- DictionaryError.new(message)
120
- end
121
- end
125
+ private
122
126
 
123
127
  def dict_manager
124
128
  @dict_manager ||= DictManager.new
125
129
  end
126
130
  end
127
131
 
128
- alias _create create
129
- alias _lookup lookup
130
-
131
- def create(**options)
132
- unknown = options.keys - %i[mode fields debug projection]
133
- raise ArgumentError, "unknown keyword(s): #{unknown.join(", ")}" unless unknown.empty?
134
-
135
- mode = options.fetch(:mode, MODE_C)
136
- fields = options.fetch(:fields, nil)
137
- debug = options.fetch(:debug, false)
138
- projection = options.fetch(:projection, nil)
139
-
140
- raise ArgumentError, "fields must be an Array<String|Symbol> or nil" unless fields.nil? || fields.is_a?(Array)
141
- if fields&.any? { !(_1.is_a?(String) || _1.is_a?(Symbol)) }
142
- raise ArgumentError, "fields must contain only String or Symbol values"
143
- end
144
- raise ArgumentError, "debug must be true or false" unless [true, false].include?(debug)
145
-
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")
146
142
  raise NotImplementedError, "projection is not supported yet" unless projection.nil?
147
143
 
148
- mode_str = Kabosu.__send__(:normalize_mode, mode)
149
- _create(mode_str, fields, debug)
144
+ fields = fields.to_a if fields.is_a?(Enumerable)
145
+ _tokenizer(mode, fields, debug)
150
146
  end
147
+ # The name this method had before SudachiPy renamed it. Not deprecated.
148
+ alias create tokenizer
151
149
 
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
152
  def lookup(text)
153
- raise ArgumentError, "text must be a String" unless text.is_a?(String)
154
-
155
- MorphemeList.new(_lookup(text))
156
- rescue RuntimeError => e
157
- raise LookupError.new(e.message), cause: e
153
+ MorphemeList.new(_lookup(Arguments.string(text, "text")))
158
154
  end
159
155
 
160
156
  # Every public dictionary entry as a standalone Morpheme (offsets cover its
@@ -170,13 +166,10 @@ module Kabosu
170
166
  end
171
167
 
172
168
  # Like #lookup, but exact matches only and found by scanning every entry,
173
- # so it also finds entries that are not indexed for lookup. Slow.
169
+ # so it also finds entries that are not indexed for lookup. Slow; other
170
+ # threads keep running during the scan.
174
171
  def lookup_all_entries(surface)
175
- raise ArgumentError, "surface must be a String" unless surface.is_a?(String)
176
-
177
- MorphemeList.new(_lookup_all_entries(surface))
178
- rescue RuntimeError => e
179
- raise LookupError.new(e.message), cause: e
172
+ MorphemeList.new(_lookup_all_entries(Arguments.string(surface, "surface")))
180
173
  end
181
174
 
182
175
  # Builds an out-of-vocabulary Morpheme by hand. The forms default to the
@@ -185,98 +178,154 @@ module Kabosu
185
178
  # dict.oov_morpheme(pos_id, "ズィーガンボルト", reading: "ズィーガンボルト")
186
179
  def oov_morpheme(pos_id, surface, reading: nil, normalized_form: nil, dictionary_form: nil)
187
180
  raise ArgumentError, "pos_id must be an Integer" unless pos_id.is_a?(Integer)
188
- raise ArgumentError, "surface must be a String" unless surface.is_a?(String)
181
+ raise ArgumentError, "invalid part-of-speech id #{pos_id}" unless pos_id.between?(0, 0xFFFF)
189
182
 
190
- _oov_morpheme(pos_id, surface, reading, normalized_form, dictionary_form)
191
- rescue RangeError, RuntimeError => e
192
- raise ArgumentError, "invalid part-of-speech id #{pos_id}: #{e.message}"
183
+ _oov_morpheme(pos_id, Arguments.string(surface, "surface"), reading, normalized_form, dictionary_form)
193
184
  end
194
- end
195
185
 
196
- # ── 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)
197
199
 
198
- class Tokenizer
199
- alias _tokenize tokenize
200
+ patterns.each do |pattern|
201
+ next unless PosMatcher.new(pattern, dictionary: self).empty?
200
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
207
+
208
+ private :_tokenizer, :_lookup, :_each_entry, :_lookup_all_entries, :_oov_morpheme
209
+ end
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.
201
215
  def tokenize(text)
202
- raise ArgumentError, "text must be a String" unless text.is_a?(String)
216
+ MorphemeList.new(_tokenize(Arguments.string(text, "text")))
217
+ end
203
218
 
204
- batch = _tokenize(text)
205
- cost = batch.respond_to?(:internal_cost) ? batch.internal_cost : nil
206
- MorphemeList.new(batch, internal_cost: cost)
207
- rescue RuntimeError => e
208
- 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) }
209
230
  end
231
+
232
+ private :_tokenize, :_tokenize_batch
210
233
  end
211
234
 
212
235
  class Morpheme
213
- 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
214
245
 
215
- def split(mode: MODE_C, add_single: true)
216
- 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
217
251
 
218
- mode_str = Kabosu.__send__(:normalize_mode, mode)
219
- MorphemeList.new(_split(mode_str, nil, add_single))
220
- rescue RuntimeError => e
221
- 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
222
256
  end
223
- end
224
257
 
225
- # Compiles user-dictionary CSV(s) into a binary user dictionary. The result
226
- # loads only next to the system dictionary it was built against, so rebuild
227
- # whenever that changes (including the move to sudachi.rs 0.7).
228
- #
229
- # Kabosu.build_user_dict("names.csv", output: "names.dic")
230
- # Kabosu::Dictionary.new(system_dict: Kabosu::Dictionary.path, user_dicts: ["names.dic"])
231
- def self.build_user_dict(inputs, output:, system_dict: Dictionary.path, description: nil)
232
- inputs = Array(inputs)
233
- raise ArgumentError, "inputs must be String paths" unless inputs.all?(String)
234
- raise ArgumentError, "output must be a String" unless output.is_a?(String)
235
-
236
- _build_user_dict(inputs, system_dict, output, description)
237
- output
238
- rescue RuntimeError => e
239
- raise DictionaryError.new(e.message), cause: e
240
- end
258
+ alias size length
241
259
 
242
- def self.split_sentences(text, limit: nil, with_checker: false, ranges: false, dictionary: nil)
243
- raise ArgumentError, "text must be a String" unless text.is_a?(String)
244
- raise ArgumentError, "limit must be an Integer or nil" unless limit.nil? || limit.is_a?(Integer)
245
- raise ArgumentError, "limit must be greater than 0" if limit && limit < 1
246
- raise ArgumentError, "with_checker must be true or false" unless [true, false].include?(with_checker)
247
- raise ArgumentError, "ranges must be true or false" unless [true, false].include?(ranges)
248
- raise ArgumentError, "dictionary must be a String path or nil" unless dictionary.nil? || dictionary.is_a?(String)
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
249
262
 
250
- dict_path = nil
251
- dict_path = dictionary || Dictionary.path if with_checker
263
+ # The morpheme as a Hash, keyed by reader name (`oov?` is `:oov`).
264
+ def to_h
265
+ deconstruct_keys(nil)
266
+ end
252
267
 
253
- if ranges
254
- _split_sentences_with_ranges(text, limit, dict_path).map do |(start, finish, sentence)|
255
- SentenceRange.new(start, finish, sentence)
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)]
256
276
  end
257
- else
258
- _split_sentences(text, limit, dict_path)
259
277
  end
260
- rescue RuntimeError => e
261
- raise SentenceSplitError.new(e.message), cause: e
278
+
279
+ private :_split
262
280
  end
263
281
 
264
- # ── Convenience tokenization ──
265
-
266
- # Tokenize text using an explicitly provided tokenizer.
267
- #
268
- # dict = Kabosu::Dictionary.new(system_dict: Kabosu::Dictionary.path)
269
- # tok = dict.create(mode: :a)
270
- # Kabosu.tokenize("東京都に住んでいる", tokenizer: tok)
271
- #
272
- def self.tokenize(text, tokenizer:)
273
- raise ArgumentError, "text must be a String" unless text.is_a?(String)
274
- raise ArgumentError, "tokenizer must be a Kabosu::Tokenizer" unless tokenizer.is_a?(Tokenizer)
275
-
276
- batch = tokenizer.__send__(:_tokenize, text)
277
- cost = batch.respond_to?(:internal_cost) ? batch.internal_cost : nil
278
- MorphemeList.new(batch, internal_cost: cost)
279
- rescue RuntimeError => e
280
- 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
281
330
  end
282
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.7.0.1
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-11-15 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