Class: Kotoshu::Algorithms::Suggest::Suggester

Inherits:
Object
  • Object
show all
Defined in:
lib/kotoshu/algorithms/suggest.rb

Overview

Main suggestion class.

Typically, you would not use this directly, but you might want to for experiments.

Example:

dictionary = Kotoshu::Dictionary.load('en_US')
suggester = dictionary.suggester

suggester.suggestions('spylls') do |suggestion|
  puts suggestion
end

# Output:
# Suggestion[badchar](spell)
# Suggestion[badchar](spill)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(aff, dic, lookup) ⇒ Suggester

Returns a new instance of Suggester.



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/kotoshu/algorithms/suggest.rb', line 130

def initialize(aff, dic, lookup)
  @aff = aff
  @dic = dic
  @lookup = lookup

  # Prepare words for ngram (exclude those with bad flags)
  bad_flags = [
    @aff[:FORBIDDENWORD],
    @aff[:NOSUGGEST],
    @aff[:ONLYINCOMPOUND]
  ].compact

  @words_for_ngram = @dic[:words].select do |word|
    flags = word[:flags] || []
    (flags & bad_flags).empty?
  end
end

Instance Attribute Details

#affObject (readonly)

Returns Aff data structure (from aff file).

Returns:

  • (Object)

    Aff data structure (from aff file)



122
123
124
# File 'lib/kotoshu/algorithms/suggest.rb', line 122

def aff
  @aff
end

#dicObject (readonly)

Returns Dic data structure (from dic file).

Returns:

  • (Object)

    Dic data structure (from dic file)



125
126
127
# File 'lib/kotoshu/algorithms/suggest.rb', line 125

def dic
  @dic
end

#lookupObject (readonly)

Returns Lookup object.

Returns:

  • (Object)

    Lookup object



128
129
130
# File 'lib/kotoshu/algorithms/suggest.rb', line 128

def lookup
  @lookup
end

Instance Method Details

#call(word) ⇒ Enumerator<String>

Outer “public” interface: returns all valid suggestions as strings.

Returns an enumerator for lazy evaluation.

Parameters:

  • word (String)

    Word to check

Returns:

  • (Enumerator<String>)

    Suggestions as strings



154
155
156
157
158
159
160
# File 'lib/kotoshu/algorithms/suggest.rb', line 154

def call(word)
  return enum_for(:call, word) unless block_given?

  suggestions(word) do |suggestion|
    yield suggestion.text
  end
end

#edit_suggestions(word, compounds:, limit:) {|Suggestion, MultiWordSuggestion| ... } ⇒ Object

Generate edit suggestions and filter for valid words.

Parameters:

  • word (String)

    Word to generate edits for

  • compounds (Boolean)

    Whether to check compound words

  • limit (Integer)

    Maximum number of suggestions to yield

Yields:



416
417
418
419
420
421
422
423
424
425
426
427
428
429
# File 'lib/kotoshu/algorithms/suggest.rb', line 416

def edit_suggestions(word, compounds:, limit:)
  count = 0

  edits(word) do |suggestion|
    break if count > limit

    # Filter for valid words
    filtered = filter_suggestion(suggestion, compounds)
    next unless filtered

    yield filtered
    count += 1
  end
end

#edits(word) {|Suggestion, MultiWordSuggestion| ... } ⇒ Object

Generate all possible word edits in order of priority.

Order is important - it’s the order user receives suggestions.

Parameters:

  • word (String)

    Word to mutate

Yields:



332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
# File 'lib/kotoshu/algorithms/suggest.rb', line 332

def edits(word)
  # Uppercase suggestion (html -> HTML)
  yield Suggestion.new(@aff[:casing].upper(word), 'uppercase')

  # REP table replacements
  reptable = @aff[:REP] || []
  Permutations.replchars(word, reptable) do |suggestion|
    if suggestion.is_a?(Array)
      # Multi-word suggestion from REP with underscore
      yield Suggestion.new(suggestion.join(' '), 'replchars')
      yield MultiWordSuggestion.new(suggestion, 'replchars', allow_dash: false)
    else
      yield Suggestion.new(suggestion, 'replchars')
    end
  end

  # Split into two words (spaceword)
  Permutations.twowords(word) do |words|
    yield Suggestion.new(words.join(' '), 'spaceword')
    yield Suggestion.new(words.join('-'), 'spaceword') if use_dash?
  end

  # MAP table (related character replacements)
  maptable = @aff[:MAP] || []
  Permutations.mapchars(word, maptable) do |suggestion|
    yield Suggestion.new(suggestion, 'mapchars')
  end

  # Swap adjacent characters
  Permutations.swapchar(word) do |suggestion|
    yield Suggestion.new(suggestion, 'swapchar')
  end

  # Long swaps (up to 4 chars distance)
  Permutations.longswapchar(word) do |suggestion|
    yield Suggestion.new(suggestion, 'longswapchar')
  end

  # Replace with keyboard-adjacent chars
  layout = @aff[:KEY] || ''
  Permutations.badcharkey(word, layout) do |suggestion|
    yield Suggestion.new(suggestion, 'badcharkey')
  end

  # Remove one character
  Permutations.extrachar(word) do |suggestion|
    yield Suggestion.new(suggestion, 'extrachar')
  end

  # Insert one character (from TRY string)
  trystring = @aff[:TRY] || ''
  Permutations.forgotchar(word, trystring) do |suggestion|
    yield Suggestion.new(suggestion, 'forgotchar')
  end

  # Move character forward/backward
  Permutations.movechar(word) do |suggestion|
    yield Suggestion.new(suggestion, 'movechar')
  end

  # Replace each character
  Permutations.badchar(word, trystring) do |suggestion|
    yield Suggestion.new(suggestion, 'badchar')
  end

  # Fix two-character doubling
  Permutations.doubletwochars(word) do |suggestion|
    yield Suggestion.new(suggestion, 'doubletwochars')
  end

  # Split by space in all positions
  unless @aff[:NOSPLITSUGS]
    Permutations.twowords(word) do |words|
      yield MultiWordSuggestion.new(words, 'twowords', allow_dash: use_dash?)
    end
  end
end

#ngram_suggestions(word, handled:) {|String| ... } ⇒ Object

Generate ngram-based suggestions.

Parameters:

  • word (String)

    Misspelled word

  • handled (Set<String>)

    Already suggested words

Yields:

  • (String)

    Each ngram suggestion



436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
# File 'lib/kotoshu/algorithms/suggest.rb', line 436

def ngram_suggestions(word, handled:)
  return unless @aff[:MAXNGRAMSUGS]&.positive?

  known_lower = handled.map(&:downcase).to_set

  NgramSuggest.suggest(
    word.downcase,
    dictionary_words: @words_for_ngram,
    prefixes: @aff[:PFX] || {},
    suffixes: @aff[:SFX] || {},
    known: known_lower,
    maxdiff: @aff[:MAXDIFF] || 2,
    onlymaxdiff: @aff[:ONLYMAXDIFF] || true,
    has_phonetic: !@aff[:PHONE].nil?
  ) do |suggestion|
    yield suggestion
  end
end

#phonet_suggestions(word) {|String| ... } ⇒ Object

Generate phonetic suggestions.

Parameters:

  • word (String)

    Misspelled word

Yields:

  • (String)

    Each phonetic suggestion



459
460
461
462
463
464
465
466
467
468
469
# File 'lib/kotoshu/algorithms/suggest.rb', line 459

def phonet_suggestions(word)
  return unless @aff[:PHONE]

  PhonetSuggest.suggest(
    word,
    dictionary_words: @words_for_ngram,
    table: @aff[:PHONE]
  ) do |suggestion|
    yield suggestion
  end
end

#suggestions(word) {|Suggestion, MultiWordSuggestion| ... } ⇒ Object

Main suggestion search loop.

What it does, in general:

  1. Generates possible misspelled word cases (capitalization variants)

  2. Produces word edits with edits, checks them with Lookup

  3. If needed, produces ngram-based suggestions

  4. If needed, produces phonetically similar suggestions

Parameters:

  • word (String)

    Word to check

Yields:



172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
# File 'lib/kotoshu/algorithms/suggest.rb', line 172

def suggestions(word)
  return enum_for(:suggestions, word) unless block_given?

  # Track all suggestions we've already yielded
  handled = Set.new

  # Helper: Check if suggestion is a valid word
  is_good_suggestion = ->(w) do
    # Check if there's any good form of this exact word
    # Note: We check good_forms directly to avoid ICONV and dash-breaking
    good_forms = @lookup.good_forms(w, capitalization: false, allow_nosuggest: false)
    good_forms.any?
  end

  # Helper: Check if word is forbidden
  is_forbidden = ->(w) do
    return false unless @aff[:FORBIDDENWORD]

    @dic[:has_flag]&.call(w, @aff[:FORBIDDENWORD]) || false
  end

  # Get capitalization type and variants
  captype, variants = @aff[:casing].corrections(word)

  # Special case: FORCEUCASE with NO capitalization
  if @aff[:FORCEUCASE] && captype == Capitalization::Type::NO
    @aff[:casing].capitalize(word).each do |capitalized|
      if is_good_suggestion.call(capitalized)
        yield Suggestion.new(capitalized.capitalize, 'forceucase')
        return
      end
    end
  end

  good_edits_found = false

  # Process each capitalization variant
  variants.each_with_index do |variant, idx|
    # If different from original and is good, suggest it
    if idx.positive? && is_good_suggestion.call(variant)
      handle_found(
        Suggestion.new(variant, 'case'),
        captype: captype,
        is_forbidden: is_forbidden,
        handled: handled
      ) do |suggestion|
        yield suggestion
      end
    end

    # Generate and check edits (non-compound first)
    nocompound = false

    edit_suggestions(variant, compounds: false, limit: MAXSUGGESTIONS) do |suggestion|
      handle_found(
        suggestion,
        captype: captype,
        is_forbidden: is_forbidden,
        handled: handled,
        check_inclusion: false
      ) do |handled_suggestion|
        yield handled_suggestion

        kind = handled_suggestion.kind
        good_edits_found = true if GOOD_EDITS.include?(kind)
        nocompound = true if %w[uppercase replchars mapchars].include?(kind)

        # If we found a spaceword that's in the dictionary as a whole,
        # that's the only suggestion we need
        return if kind == 'spaceword'
      end
    end

    # Generate compound suggestions if not excluded
    unless nocompound
      limit = @aff[:MAXCPDSUGS] || MAXSUGGESTIONS
      edit_suggestions(variant, compounds: true, limit: limit) do |suggestion|
        handle_found(
          suggestion,
          captype: captype,
          is_forbidden: is_forbidden,
          handled: handled,
          check_inclusion: false
        ) do |handled_suggestion|
          yield handled_suggestion
          kind = handled_suggestion.kind
          good_edits_found = true if GOOD_EDITS.include?(kind)
        end
      end
    end
  end

  # Skip ngram/phonetic if we found good edits
  return if good_edits_found

  # Try fixing words with dashes
  if word.include?('-') && handled.none? { |s| s.include?('-') }
    chunks = word.split('-')
    chunks.each_with_index do |chunk, idx|
      next if is_good_suggestion.call(chunk)

      # Try all suggestions for this chunk
      call(chunk).each do |sug|
        candidate = chunks[0...idx] + [sug] + chunks[(idx + 1)..]
        candidate_str = candidate.join('-')

        # Check if the whole word with replacement is good
        if @lookup.call(candidate_str, capitalization: true, allow_nosuggest: true)
          yield Suggestion.new(candidate_str, 'dashes')
        end
      end

      # Only try one misspelled chunk
      break
    end
  end

  # Ngram-based suggestions
  if @aff[:MAXNGRAMSUGS]&.positive?
    ngrams_seen = 0
    ngram_suggestions(word, handled: handled) do |sug|
      handle_found(
        Suggestion.new(sug, 'ngram'),
        captype: captype,
        is_forbidden: is_forbidden,
        handled: handled,
        check_inclusion: true
      ) do |suggestion|
        yield suggestion
        ngrams_seen += 1
        break if ngrams_seen >= @aff[:MAXNGRAMSUGS]
      end
    end
  end

  # Phonetic suggestions
  if @aff[:PHONE]
    phonet_seen = 0
    phonet_suggestions(word) do |sug|
      handle_found(
        Suggestion.new(sug, 'phonet'),
        captype: captype,
        is_forbidden: is_forbidden,
        handled: handled,
        check_inclusion: true
      ) do |suggestion|
        yield suggestion
        phonet_seen += 1
        break if phonet_seen >= MAXPHONSUGS
      end
    end
  end
end

#use_dash?Boolean

Check if dashes are allowed for joining words.

Definition from Hunspell: Either dash is in TRY directive, or TRY indicates Latinic script (by having ‘a’).

Returns:

  • (Boolean)

    Whether dashes are allowed



477
478
479
480
# File 'lib/kotoshu/algorithms/suggest.rb', line 477

def use_dash?
  try_chars = @aff[:TRY] || ''
  try_chars.include?('-') || try_chars.include?('a')
end