You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@lucene.apache.org by GitBox <gi...@apache.org> on 2021/02/08 10:28:47 UTC

[GitHub] [lucene-solr] donnerpeter opened a new pull request #2320: LUCENE-9742: Hunspell: suggest dictionary entries similar to the misspelled word

donnerpeter opened a new pull request #2320:
URL: https://github.com/apache/lucene-solr/pull/2320


   <!--
   _(If you are a project committer then you may remove some/all of the following template.)_
   
   Before creating a pull request, please file an issue in the ASF Jira system for Lucene or Solr:
   
   * https://issues.apache.org/jira/projects/LUCENE
   * https://issues.apache.org/jira/projects/SOLR
   
   You will need to create an account in Jira in order to create an issue.
   
   The title of the PR should reference the Jira issue number in the form:
   
   * LUCENE-####: <short description of problem or changes>
   * SOLR-####: <short description of problem or changes>
   
   LUCENE and SOLR must be fully capitalized. A short description helps people scanning pull requests for items they can work on.
   
   Properly referencing the issue in the title ensures that Jira is correctly updated with code review comments and commits. -->
   
   
   # Description
   
   Hunspell has "ngram-based suggestions" where the dictionary is enumerated, forms are derived, and checked whether the result is similar to the misspelled word.
   
   # Solution
   
   Here I start implementing this functionality, without affixes so far.
   
   # Tests
   
   3 suggestion tests from Hunspell repo are now added
   
   # Checklist
   
   Please review the following and check all that apply:
   
   - [x] I have reviewed the guidelines for [How to Contribute](https://wiki.apache.org/solr/HowToContribute) and my code conforms to the standards described there to the best of my ability.
   - [x] I have created a Jira issue and added the issue ID to my pull request title.
   - [x] I have given Solr maintainers [access](https://help.github.com/en/articles/allowing-changes-to-a-pull-request-branch-created-from-a-fork) to contribute to my PR branch. (optional but recommended)
   - [x] I have developed this patch against the `master` branch.
   - [x] I have run `./gradlew check`.
   - [x] I have added tests for my changes.
   - [ ] I have added documentation for the [Ref Guide](https://github.com/apache/lucene-solr/tree/master/solr/solr-ref-guide) (for Solr changes only).
   


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@lucene.apache.org
For additional commands, e-mail: issues-help@lucene.apache.org


[GitHub] [lucene-solr] donnerpeter commented on a change in pull request #2320: LUCENE-9742: Hunspell: suggest dictionary entries similar to the misspelled word

Posted by GitBox <gi...@apache.org>.
donnerpeter commented on a change in pull request #2320:
URL: https://github.com/apache/lucene-solr/pull/2320#discussion_r571936064



##########
File path: lucene/analysis/common/src/java/org/apache/lucene/analysis/hunspell/GeneratingSuggester.java
##########
@@ -0,0 +1,321 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.lucene.analysis.hunspell;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.EnumSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.stream.Collectors;
+import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.fst.IntsRefFSTEnum;
+
+/**
+ * A class that traverses the entire dictionary and applies affix rules to check if those yield
+ * correct suggestions similar enough to the given misspelled word
+ */
+class GeneratingSuggester {
+  private static final int MAX_ROOTS = 100;
+  private static final int MAX_GUESSES = 100;
+  private final Dictionary dictionary;
+
+  GeneratingSuggester(Dictionary dictionary) {
+    this.dictionary = dictionary;
+  }
+
+  List<String> suggest(String word, WordCase originalCase, Set<String> prevSuggestions) {
+    List<WeightedWord> roots = findSimilarDictionaryEntries(word, originalCase);
+    List<WeightedWord> expanded = expandRoots(word, roots);
+    TreeSet<WeightedWord> bySimilarity = rankBySimilarity(word, expanded);
+    return getMostRelevantSuggestions(bySimilarity, prevSuggestions);
+  }
+
+  private List<WeightedWord> findSimilarDictionaryEntries(String word, WordCase originalCase) {
+    try {
+      IntsRefFSTEnum<IntsRef> fstEnum = new IntsRefFSTEnum<>(dictionary.words);
+      TreeSet<WeightedWord> roots = new TreeSet<>();
+
+      IntsRefFSTEnum.InputOutput<IntsRef> mapping;
+      while ((mapping = fstEnum.next()) != null) {
+        IntsRef key = mapping.input;
+        if (Math.abs(key.length - word.length()) > 4 || !isSuitableRoot(mapping.output)) continue;
+
+        String root = toString(key);
+        if (originalCase == WordCase.LOWER
+            && WordCase.caseOf(root) == WordCase.TITLE
+            && !dictionary.hasLanguage("de")) {
+          continue;
+        }
+
+        String lower = dictionary.toLowerCase(root);
+        int sc =
+            ngram(3, word, lower, EnumSet.of(NGramOptions.LONGER_WORSE)) + commonPrefix(word, root);
+
+        roots.add(new WeightedWord(root, sc));
+      }
+      return roots.stream().limit(MAX_ROOTS).collect(Collectors.toList());
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  private static String toString(IntsRef key) {
+    char[] chars = new char[key.length];
+    for (int i = 0; i < key.length; i++) {
+      chars[i] = (char) key.ints[i + key.offset];
+    }
+    return new String(chars);
+  }
+
+  private boolean isSuitableRoot(IntsRef forms) {
+    for (int i = 0; i < forms.length; i += dictionary.formStep()) {
+      int entryId = forms.ints[forms.offset + i];
+      if (dictionary.hasFlag(entryId, dictionary.needaffix)
+          || dictionary.hasFlag(entryId, dictionary.forbiddenword)
+          || dictionary.hasFlag(entryId, Dictionary.HIDDEN_FLAG)
+          || dictionary.hasFlag(entryId, dictionary.onlyincompound)) {
+        continue;
+      }
+      return true;
+    }
+
+    return false;
+  }
+
+  private List<WeightedWord> expandRoots(String word, List<WeightedWord> roots) {
+    int thresh = calcThreshold(word);
+
+    TreeSet<WeightedWord> expanded = new TreeSet<>();
+    for (WeightedWord weighted : roots) {
+      String guess = weighted.word;
+      String lower = dictionary.toLowerCase(guess);
+      int sc =
+          ngram(word.length(), word, lower, EnumSet.of(NGramOptions.ANY_MISMATCH))
+              + commonPrefix(word, guess);
+      if (sc > thresh) {
+        expanded.add(new WeightedWord(guess, sc));
+      }
+    }
+    return expanded.stream().limit(MAX_GUESSES).collect(Collectors.toList());
+  }
+
+  // find minimum threshold for a passable suggestion
+  // mangle original word three different ways
+  // and score them to generate a minimum acceptable score
+  private static int calcThreshold(String word) {
+    int thresh = 0;
+    for (int sp = 1; sp < 4; sp++) {
+      char[] mw = word.toCharArray();
+      for (int k = sp; k < word.length(); k += 4) {
+        mw[k] = '*';
+      }
+
+      thresh += ngram(word.length(), word, new String(mw), EnumSet.of(NGramOptions.ANY_MISMATCH));
+    }
+    return thresh / 3 - 1;
+  }
+
+  private TreeSet<WeightedWord> rankBySimilarity(String word, List<WeightedWord> expanded) {
+    double fact = (10.0 - dictionary.maxDiff) / 5.0;
+    TreeSet<WeightedWord> bySimilarity = new TreeSet<>();
+    for (WeightedWord weighted : expanded) {
+      String guess = weighted.word;
+      String lower = dictionary.toLowerCase(guess);
+      if (lower.equals(word)) {
+        bySimilarity.add(new WeightedWord(guess, weighted.score + 2000));
+        break;
+      }
+
+      int re =
+          ngram(2, word, lower, EnumSet.of(NGramOptions.ANY_MISMATCH, NGramOptions.WEIGHTED))
+              + ngram(2, lower, word, EnumSet.of(NGramOptions.ANY_MISMATCH, NGramOptions.WEIGHTED));
+
+      int score =
+          2 * lcs(word, lower)
+              - Math.abs(word.length() - lower.length())
+              + commonCharacterPositionScore(word, lower)
+              + commonPrefix(word, lower)
+              + ngram(4, word, lower, EnumSet.of(NGramOptions.ANY_MISMATCH))
+              + re
+              + (re < (word.length() + lower.length()) * fact ? -1000 : 0);
+      bySimilarity.add(new WeightedWord(guess, score));
+    }
+    return bySimilarity;
+  }
+
+  private List<String> getMostRelevantSuggestions(
+      TreeSet<WeightedWord> bySimilarity, Set<String> prevSuggestions) {
+    List<String> result = new ArrayList<>();
+    boolean hasExcellent = false;
+    for (WeightedWord weighted : bySimilarity) {
+      if (weighted.score > 1000) {
+        hasExcellent = true;
+      } else if (hasExcellent) {
+        break; // leave only excellent suggestions, if any
+      }
+
+      boolean bad = weighted.score < -100;
+      // keep the best ngram suggestions, unless in ONLYMAXDIFF mode
+      if (bad && (!result.isEmpty() || dictionary.onlyMaxDiff)) {
+        break;
+      }
+
+      if (prevSuggestions.stream().noneMatch(weighted.word::contains)
+          && result.stream().noneMatch(weighted.word::contains)) {
+        result.add(weighted.word);
+        if (result.size() > dictionary.maxNGramSuggestions) {
+          break;
+        }
+      }
+
+      if (bad) {
+        break;
+      }
+    }
+    return result;
+  }
+
+  private static int commonPrefix(String s1, String s2) {

Review comment:
       Is there a util for this?




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@lucene.apache.org
For additional commands, e-mail: issues-help@lucene.apache.org


[GitHub] [lucene-solr] donnerpeter commented on a change in pull request #2320: LUCENE-9742: Hunspell: suggest dictionary entries similar to the misspelled word

Posted by GitBox <gi...@apache.org>.
donnerpeter commented on a change in pull request #2320:
URL: https://github.com/apache/lucene-solr/pull/2320#discussion_r571936064



##########
File path: lucene/analysis/common/src/java/org/apache/lucene/analysis/hunspell/GeneratingSuggester.java
##########
@@ -0,0 +1,321 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.lucene.analysis.hunspell;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.EnumSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.stream.Collectors;
+import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.fst.IntsRefFSTEnum;
+
+/**
+ * A class that traverses the entire dictionary and applies affix rules to check if those yield
+ * correct suggestions similar enough to the given misspelled word
+ */
+class GeneratingSuggester {
+  private static final int MAX_ROOTS = 100;
+  private static final int MAX_GUESSES = 100;
+  private final Dictionary dictionary;
+
+  GeneratingSuggester(Dictionary dictionary) {
+    this.dictionary = dictionary;
+  }
+
+  List<String> suggest(String word, WordCase originalCase, Set<String> prevSuggestions) {
+    List<WeightedWord> roots = findSimilarDictionaryEntries(word, originalCase);
+    List<WeightedWord> expanded = expandRoots(word, roots);
+    TreeSet<WeightedWord> bySimilarity = rankBySimilarity(word, expanded);
+    return getMostRelevantSuggestions(bySimilarity, prevSuggestions);
+  }
+
+  private List<WeightedWord> findSimilarDictionaryEntries(String word, WordCase originalCase) {
+    try {
+      IntsRefFSTEnum<IntsRef> fstEnum = new IntsRefFSTEnum<>(dictionary.words);
+      TreeSet<WeightedWord> roots = new TreeSet<>();
+
+      IntsRefFSTEnum.InputOutput<IntsRef> mapping;
+      while ((mapping = fstEnum.next()) != null) {
+        IntsRef key = mapping.input;
+        if (Math.abs(key.length - word.length()) > 4 || !isSuitableRoot(mapping.output)) continue;
+
+        String root = toString(key);
+        if (originalCase == WordCase.LOWER
+            && WordCase.caseOf(root) == WordCase.TITLE
+            && !dictionary.hasLanguage("de")) {
+          continue;
+        }
+
+        String lower = dictionary.toLowerCase(root);
+        int sc =
+            ngram(3, word, lower, EnumSet.of(NGramOptions.LONGER_WORSE)) + commonPrefix(word, root);
+
+        roots.add(new WeightedWord(root, sc));
+      }
+      return roots.stream().limit(MAX_ROOTS).collect(Collectors.toList());
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  private static String toString(IntsRef key) {
+    char[] chars = new char[key.length];
+    for (int i = 0; i < key.length; i++) {
+      chars[i] = (char) key.ints[i + key.offset];
+    }
+    return new String(chars);
+  }
+
+  private boolean isSuitableRoot(IntsRef forms) {
+    for (int i = 0; i < forms.length; i += dictionary.formStep()) {
+      int entryId = forms.ints[forms.offset + i];
+      if (dictionary.hasFlag(entryId, dictionary.needaffix)
+          || dictionary.hasFlag(entryId, dictionary.forbiddenword)
+          || dictionary.hasFlag(entryId, Dictionary.HIDDEN_FLAG)
+          || dictionary.hasFlag(entryId, dictionary.onlyincompound)) {
+        continue;
+      }
+      return true;
+    }
+
+    return false;
+  }
+
+  private List<WeightedWord> expandRoots(String word, List<WeightedWord> roots) {
+    int thresh = calcThreshold(word);
+
+    TreeSet<WeightedWord> expanded = new TreeSet<>();
+    for (WeightedWord weighted : roots) {
+      String guess = weighted.word;
+      String lower = dictionary.toLowerCase(guess);
+      int sc =
+          ngram(word.length(), word, lower, EnumSet.of(NGramOptions.ANY_MISMATCH))
+              + commonPrefix(word, guess);
+      if (sc > thresh) {
+        expanded.add(new WeightedWord(guess, sc));
+      }
+    }
+    return expanded.stream().limit(MAX_GUESSES).collect(Collectors.toList());
+  }
+
+  // find minimum threshold for a passable suggestion
+  // mangle original word three different ways
+  // and score them to generate a minimum acceptable score
+  private static int calcThreshold(String word) {
+    int thresh = 0;
+    for (int sp = 1; sp < 4; sp++) {
+      char[] mw = word.toCharArray();
+      for (int k = sp; k < word.length(); k += 4) {
+        mw[k] = '*';
+      }
+
+      thresh += ngram(word.length(), word, new String(mw), EnumSet.of(NGramOptions.ANY_MISMATCH));
+    }
+    return thresh / 3 - 1;
+  }
+
+  private TreeSet<WeightedWord> rankBySimilarity(String word, List<WeightedWord> expanded) {
+    double fact = (10.0 - dictionary.maxDiff) / 5.0;
+    TreeSet<WeightedWord> bySimilarity = new TreeSet<>();
+    for (WeightedWord weighted : expanded) {
+      String guess = weighted.word;
+      String lower = dictionary.toLowerCase(guess);
+      if (lower.equals(word)) {
+        bySimilarity.add(new WeightedWord(guess, weighted.score + 2000));
+        break;
+      }
+
+      int re =
+          ngram(2, word, lower, EnumSet.of(NGramOptions.ANY_MISMATCH, NGramOptions.WEIGHTED))
+              + ngram(2, lower, word, EnumSet.of(NGramOptions.ANY_MISMATCH, NGramOptions.WEIGHTED));
+
+      int score =
+          2 * lcs(word, lower)
+              - Math.abs(word.length() - lower.length())
+              + commonCharacterPositionScore(word, lower)
+              + commonPrefix(word, lower)
+              + ngram(4, word, lower, EnumSet.of(NGramOptions.ANY_MISMATCH))
+              + re
+              + (re < (word.length() + lower.length()) * fact ? -1000 : 0);
+      bySimilarity.add(new WeightedWord(guess, score));
+    }
+    return bySimilarity;
+  }
+
+  private List<String> getMostRelevantSuggestions(
+      TreeSet<WeightedWord> bySimilarity, Set<String> prevSuggestions) {
+    List<String> result = new ArrayList<>();
+    boolean hasExcellent = false;
+    for (WeightedWord weighted : bySimilarity) {
+      if (weighted.score > 1000) {
+        hasExcellent = true;
+      } else if (hasExcellent) {
+        break; // leave only excellent suggestions, if any
+      }
+
+      boolean bad = weighted.score < -100;
+      // keep the best ngram suggestions, unless in ONLYMAXDIFF mode
+      if (bad && (!result.isEmpty() || dictionary.onlyMaxDiff)) {
+        break;
+      }
+
+      if (prevSuggestions.stream().noneMatch(weighted.word::contains)
+          && result.stream().noneMatch(weighted.word::contains)) {
+        result.add(weighted.word);
+        if (result.size() > dictionary.maxNGramSuggestions) {
+          break;
+        }
+      }
+
+      if (bad) {
+        break;
+      }
+    }
+    return result;
+  }
+
+  private static int commonPrefix(String s1, String s2) {

Review comment:
       Is there a util for common prefix?




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@lucene.apache.org
For additional commands, e-mail: issues-help@lucene.apache.org


[GitHub] [lucene-solr] donnerpeter commented on pull request #2320: LUCENE-9742: Hunspell: suggest dictionary entries similar to the misspelled word

Posted by GitBox <gi...@apache.org>.
donnerpeter commented on pull request #2320:
URL: https://github.com/apache/lucene-solr/pull/2320#issuecomment-775707413


   AFAIK JIT compiler should inline `length()` unconditionally, extract it here to a local variable, and thus there'd be just 2 comparisons instead of 1. I haven't checked the assembly though. Anyway, done.


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@lucene.apache.org
For additional commands, e-mail: issues-help@lucene.apache.org


[GitHub] [lucene-solr] donnerpeter commented on pull request #2320: LUCENE-9742: Hunspell: suggest dictionary entries similar to the misspelled word

Posted by GitBox <gi...@apache.org>.
donnerpeter commented on pull request #2320:
URL: https://github.com/apache/lucene-solr/pull/2320#issuecomment-775464056


   Hmm, I can't reply to comments in place :(
   
   > int max = Math.min(s1.length(), s2.length())
   
   Possible, but it's an additional line of code without much performance benefit. Do you think it's worth it?
   
   > If it's the length you need, not the subsequence, this can be optimized to store just one row/ column of memory, not the whole table?
   
   Indeed! I'll try it and see if the code doesn't become more obscure.
   


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@lucene.apache.org
For additional commands, e-mail: issues-help@lucene.apache.org


[GitHub] [lucene-solr] dweiss commented on a change in pull request #2320: LUCENE-9742: Hunspell: suggest dictionary entries similar to the misspelled word

Posted by GitBox <gi...@apache.org>.
dweiss commented on a change in pull request #2320:
URL: https://github.com/apache/lucene-solr/pull/2320#discussion_r572350066



##########
File path: lucene/analysis/common/src/java/org/apache/lucene/analysis/hunspell/GeneratingSuggester.java
##########
@@ -0,0 +1,321 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.lucene.analysis.hunspell;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.EnumSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.stream.Collectors;
+import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.fst.IntsRefFSTEnum;
+
+/**
+ * A class that traverses the entire dictionary and applies affix rules to check if those yield
+ * correct suggestions similar enough to the given misspelled word
+ */
+class GeneratingSuggester {
+  private static final int MAX_ROOTS = 100;
+  private static final int MAX_GUESSES = 100;
+  private final Dictionary dictionary;
+
+  GeneratingSuggester(Dictionary dictionary) {
+    this.dictionary = dictionary;
+  }
+
+  List<String> suggest(String word, WordCase originalCase, Set<String> prevSuggestions) {
+    List<WeightedWord> roots = findSimilarDictionaryEntries(word, originalCase);
+    List<WeightedWord> expanded = expandRoots(word, roots);
+    TreeSet<WeightedWord> bySimilarity = rankBySimilarity(word, expanded);
+    return getMostRelevantSuggestions(bySimilarity, prevSuggestions);
+  }
+
+  private List<WeightedWord> findSimilarDictionaryEntries(String word, WordCase originalCase) {
+    try {
+      IntsRefFSTEnum<IntsRef> fstEnum = new IntsRefFSTEnum<>(dictionary.words);
+      TreeSet<WeightedWord> roots = new TreeSet<>();
+
+      IntsRefFSTEnum.InputOutput<IntsRef> mapping;
+      while ((mapping = fstEnum.next()) != null) {
+        IntsRef key = mapping.input;
+        if (Math.abs(key.length - word.length()) > 4 || !isSuitableRoot(mapping.output)) continue;
+
+        String root = toString(key);
+        if (originalCase == WordCase.LOWER
+            && WordCase.caseOf(root) == WordCase.TITLE
+            && !dictionary.hasLanguage("de")) {
+          continue;
+        }
+
+        String lower = dictionary.toLowerCase(root);
+        int sc =
+            ngram(3, word, lower, EnumSet.of(NGramOptions.LONGER_WORSE)) + commonPrefix(word, root);
+
+        roots.add(new WeightedWord(root, sc));
+      }
+      return roots.stream().limit(MAX_ROOTS).collect(Collectors.toList());
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  private static String toString(IntsRef key) {
+    char[] chars = new char[key.length];
+    for (int i = 0; i < key.length; i++) {
+      chars[i] = (char) key.ints[i + key.offset];
+    }
+    return new String(chars);
+  }
+
+  private boolean isSuitableRoot(IntsRef forms) {
+    for (int i = 0; i < forms.length; i += dictionary.formStep()) {
+      int entryId = forms.ints[forms.offset + i];
+      if (dictionary.hasFlag(entryId, dictionary.needaffix)
+          || dictionary.hasFlag(entryId, dictionary.forbiddenword)
+          || dictionary.hasFlag(entryId, Dictionary.HIDDEN_FLAG)
+          || dictionary.hasFlag(entryId, dictionary.onlyincompound)) {
+        continue;
+      }
+      return true;
+    }
+
+    return false;
+  }
+
+  private List<WeightedWord> expandRoots(String word, List<WeightedWord> roots) {
+    int thresh = calcThreshold(word);
+
+    TreeSet<WeightedWord> expanded = new TreeSet<>();
+    for (WeightedWord weighted : roots) {
+      String guess = weighted.word;
+      String lower = dictionary.toLowerCase(guess);
+      int sc =
+          ngram(word.length(), word, lower, EnumSet.of(NGramOptions.ANY_MISMATCH))
+              + commonPrefix(word, guess);
+      if (sc > thresh) {
+        expanded.add(new WeightedWord(guess, sc));
+      }
+    }
+    return expanded.stream().limit(MAX_GUESSES).collect(Collectors.toList());
+  }
+
+  // find minimum threshold for a passable suggestion
+  // mangle original word three different ways
+  // and score them to generate a minimum acceptable score
+  private static int calcThreshold(String word) {
+    int thresh = 0;
+    for (int sp = 1; sp < 4; sp++) {
+      char[] mw = word.toCharArray();
+      for (int k = sp; k < word.length(); k += 4) {
+        mw[k] = '*';
+      }
+
+      thresh += ngram(word.length(), word, new String(mw), EnumSet.of(NGramOptions.ANY_MISMATCH));
+    }
+    return thresh / 3 - 1;
+  }
+
+  private TreeSet<WeightedWord> rankBySimilarity(String word, List<WeightedWord> expanded) {
+    double fact = (10.0 - dictionary.maxDiff) / 5.0;
+    TreeSet<WeightedWord> bySimilarity = new TreeSet<>();
+    for (WeightedWord weighted : expanded) {
+      String guess = weighted.word;
+      String lower = dictionary.toLowerCase(guess);
+      if (lower.equals(word)) {
+        bySimilarity.add(new WeightedWord(guess, weighted.score + 2000));
+        break;
+      }
+
+      int re =
+          ngram(2, word, lower, EnumSet.of(NGramOptions.ANY_MISMATCH, NGramOptions.WEIGHTED))
+              + ngram(2, lower, word, EnumSet.of(NGramOptions.ANY_MISMATCH, NGramOptions.WEIGHTED));
+
+      int score =
+          2 * lcs(word, lower)
+              - Math.abs(word.length() - lower.length())
+              + commonCharacterPositionScore(word, lower)
+              + commonPrefix(word, lower)
+              + ngram(4, word, lower, EnumSet.of(NGramOptions.ANY_MISMATCH))
+              + re
+              + (re < (word.length() + lower.length()) * fact ? -1000 : 0);
+      bySimilarity.add(new WeightedWord(guess, score));
+    }
+    return bySimilarity;
+  }
+
+  private List<String> getMostRelevantSuggestions(
+      TreeSet<WeightedWord> bySimilarity, Set<String> prevSuggestions) {
+    List<String> result = new ArrayList<>();
+    boolean hasExcellent = false;
+    for (WeightedWord weighted : bySimilarity) {
+      if (weighted.score > 1000) {
+        hasExcellent = true;
+      } else if (hasExcellent) {
+        break; // leave only excellent suggestions, if any
+      }
+
+      boolean bad = weighted.score < -100;
+      // keep the best ngram suggestions, unless in ONLYMAXDIFF mode
+      if (bad && (!result.isEmpty() || dictionary.onlyMaxDiff)) {
+        break;
+      }
+
+      if (prevSuggestions.stream().noneMatch(weighted.word::contains)
+          && result.stream().noneMatch(weighted.word::contains)) {
+        result.add(weighted.word);
+        if (result.size() > dictionary.maxNGramSuggestions) {
+          break;
+        }
+      }
+
+      if (bad) {
+        break;
+      }
+    }
+    return result;
+  }
+
+  private static int commonPrefix(String s1, String s2) {
+    int i = 0;
+    while (i < s1.length() && i < s2.length() && s1.charAt(i) == s2.charAt(i)) {

Review comment:
       int max = Math.min(s1.length(), s2.length())
   while (i < max && ... ) {
   }
   ?




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@lucene.apache.org
For additional commands, e-mail: issues-help@lucene.apache.org


[GitHub] [lucene-solr] dweiss commented on pull request #2320: LUCENE-9742: Hunspell: suggest dictionary entries similar to the misspelled word

Posted by GitBox <gi...@apache.org>.
dweiss commented on pull request #2320:
URL: https://github.com/apache/lucene-solr/pull/2320#issuecomment-775486902


   I think it's worth it - you compute it once before the loop and you can see it's a constant. Why so sure String.length() is always precomputed? :) 


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@lucene.apache.org
For additional commands, e-mail: issues-help@lucene.apache.org


[GitHub] [lucene-solr] donnerpeter commented on a change in pull request #2320: LUCENE-9742: Hunspell: suggest dictionary entries similar to the misspelled word

Posted by GitBox <gi...@apache.org>.
donnerpeter commented on a change in pull request #2320:
URL: https://github.com/apache/lucene-solr/pull/2320#discussion_r571935196



##########
File path: lucene/analysis/common/src/java/org/apache/lucene/analysis/hunspell/GeneratingSuggester.java
##########
@@ -0,0 +1,321 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.lucene.analysis.hunspell;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.EnumSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.stream.Collectors;
+import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.fst.IntsRefFSTEnum;
+
+/**
+ * A class that traverses the entire dictionary and applies affix rules to check if those yield
+ * correct suggestions similar enough to the given misspelled word
+ */
+class GeneratingSuggester {
+  private static final int MAX_ROOTS = 100;
+  private static final int MAX_GUESSES = 100;
+  private final Dictionary dictionary;
+
+  GeneratingSuggester(Dictionary dictionary) {
+    this.dictionary = dictionary;
+  }
+
+  List<String> suggest(String word, WordCase originalCase, Set<String> prevSuggestions) {
+    List<WeightedWord> roots = findSimilarDictionaryEntries(word, originalCase);
+    List<WeightedWord> expanded = expandRoots(word, roots);
+    TreeSet<WeightedWord> bySimilarity = rankBySimilarity(word, expanded);
+    return getMostRelevantSuggestions(bySimilarity, prevSuggestions);
+  }
+
+  private List<WeightedWord> findSimilarDictionaryEntries(String word, WordCase originalCase) {
+    try {
+      IntsRefFSTEnum<IntsRef> fstEnum = new IntsRefFSTEnum<>(dictionary.words);
+      TreeSet<WeightedWord> roots = new TreeSet<>();
+
+      IntsRefFSTEnum.InputOutput<IntsRef> mapping;
+      while ((mapping = fstEnum.next()) != null) {
+        IntsRef key = mapping.input;
+        if (Math.abs(key.length - word.length()) > 4 || !isSuitableRoot(mapping.output)) continue;
+
+        String root = toString(key);
+        if (originalCase == WordCase.LOWER
+            && WordCase.caseOf(root) == WordCase.TITLE
+            && !dictionary.hasLanguage("de")) {
+          continue;
+        }
+
+        String lower = dictionary.toLowerCase(root);
+        int sc =
+            ngram(3, word, lower, EnumSet.of(NGramOptions.LONGER_WORSE)) + commonPrefix(word, root);
+
+        roots.add(new WeightedWord(root, sc));
+      }
+      return roots.stream().limit(MAX_ROOTS).collect(Collectors.toList());
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  private static String toString(IntsRef key) {
+    char[] chars = new char[key.length];
+    for (int i = 0; i < key.length; i++) {
+      chars[i] = (char) key.ints[i + key.offset];
+    }
+    return new String(chars);
+  }
+
+  private boolean isSuitableRoot(IntsRef forms) {
+    for (int i = 0; i < forms.length; i += dictionary.formStep()) {
+      int entryId = forms.ints[forms.offset + i];
+      if (dictionary.hasFlag(entryId, dictionary.needaffix)
+          || dictionary.hasFlag(entryId, dictionary.forbiddenword)
+          || dictionary.hasFlag(entryId, Dictionary.HIDDEN_FLAG)
+          || dictionary.hasFlag(entryId, dictionary.onlyincompound)) {
+        continue;
+      }
+      return true;
+    }
+
+    return false;
+  }
+
+  private List<WeightedWord> expandRoots(String word, List<WeightedWord> roots) {
+    int thresh = calcThreshold(word);
+
+    TreeSet<WeightedWord> expanded = new TreeSet<>();
+    for (WeightedWord weighted : roots) {
+      String guess = weighted.word;

Review comment:
       To be affixed in a future patch




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@lucene.apache.org
For additional commands, e-mail: issues-help@lucene.apache.org


[GitHub] [lucene-solr] dweiss commented on a change in pull request #2320: LUCENE-9742: Hunspell: suggest dictionary entries similar to the misspelled word

Posted by GitBox <gi...@apache.org>.
dweiss commented on a change in pull request #2320:
URL: https://github.com/apache/lucene-solr/pull/2320#discussion_r572352850



##########
File path: lucene/analysis/common/src/java/org/apache/lucene/analysis/hunspell/GeneratingSuggester.java
##########
@@ -0,0 +1,321 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.lucene.analysis.hunspell;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.EnumSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.stream.Collectors;
+import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.fst.IntsRefFSTEnum;
+
+/**
+ * A class that traverses the entire dictionary and applies affix rules to check if those yield
+ * correct suggestions similar enough to the given misspelled word
+ */
+class GeneratingSuggester {
+  private static final int MAX_ROOTS = 100;
+  private static final int MAX_GUESSES = 100;
+  private final Dictionary dictionary;
+
+  GeneratingSuggester(Dictionary dictionary) {
+    this.dictionary = dictionary;
+  }
+
+  List<String> suggest(String word, WordCase originalCase, Set<String> prevSuggestions) {
+    List<WeightedWord> roots = findSimilarDictionaryEntries(word, originalCase);
+    List<WeightedWord> expanded = expandRoots(word, roots);
+    TreeSet<WeightedWord> bySimilarity = rankBySimilarity(word, expanded);
+    return getMostRelevantSuggestions(bySimilarity, prevSuggestions);
+  }
+
+  private List<WeightedWord> findSimilarDictionaryEntries(String word, WordCase originalCase) {
+    try {
+      IntsRefFSTEnum<IntsRef> fstEnum = new IntsRefFSTEnum<>(dictionary.words);
+      TreeSet<WeightedWord> roots = new TreeSet<>();
+
+      IntsRefFSTEnum.InputOutput<IntsRef> mapping;
+      while ((mapping = fstEnum.next()) != null) {
+        IntsRef key = mapping.input;
+        if (Math.abs(key.length - word.length()) > 4 || !isSuitableRoot(mapping.output)) continue;
+
+        String root = toString(key);
+        if (originalCase == WordCase.LOWER
+            && WordCase.caseOf(root) == WordCase.TITLE
+            && !dictionary.hasLanguage("de")) {
+          continue;
+        }
+
+        String lower = dictionary.toLowerCase(root);
+        int sc =
+            ngram(3, word, lower, EnumSet.of(NGramOptions.LONGER_WORSE)) + commonPrefix(word, root);
+
+        roots.add(new WeightedWord(root, sc));
+      }
+      return roots.stream().limit(MAX_ROOTS).collect(Collectors.toList());
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  private static String toString(IntsRef key) {
+    char[] chars = new char[key.length];
+    for (int i = 0; i < key.length; i++) {
+      chars[i] = (char) key.ints[i + key.offset];
+    }
+    return new String(chars);
+  }
+
+  private boolean isSuitableRoot(IntsRef forms) {
+    for (int i = 0; i < forms.length; i += dictionary.formStep()) {
+      int entryId = forms.ints[forms.offset + i];
+      if (dictionary.hasFlag(entryId, dictionary.needaffix)
+          || dictionary.hasFlag(entryId, dictionary.forbiddenword)
+          || dictionary.hasFlag(entryId, Dictionary.HIDDEN_FLAG)
+          || dictionary.hasFlag(entryId, dictionary.onlyincompound)) {
+        continue;
+      }
+      return true;
+    }
+
+    return false;
+  }
+
+  private List<WeightedWord> expandRoots(String word, List<WeightedWord> roots) {
+    int thresh = calcThreshold(word);
+
+    TreeSet<WeightedWord> expanded = new TreeSet<>();
+    for (WeightedWord weighted : roots) {
+      String guess = weighted.word;
+      String lower = dictionary.toLowerCase(guess);
+      int sc =
+          ngram(word.length(), word, lower, EnumSet.of(NGramOptions.ANY_MISMATCH))
+              + commonPrefix(word, guess);
+      if (sc > thresh) {
+        expanded.add(new WeightedWord(guess, sc));
+      }
+    }
+    return expanded.stream().limit(MAX_GUESSES).collect(Collectors.toList());
+  }
+
+  // find minimum threshold for a passable suggestion
+  // mangle original word three different ways
+  // and score them to generate a minimum acceptable score
+  private static int calcThreshold(String word) {
+    int thresh = 0;
+    for (int sp = 1; sp < 4; sp++) {
+      char[] mw = word.toCharArray();
+      for (int k = sp; k < word.length(); k += 4) {
+        mw[k] = '*';
+      }
+
+      thresh += ngram(word.length(), word, new String(mw), EnumSet.of(NGramOptions.ANY_MISMATCH));
+    }
+    return thresh / 3 - 1;
+  }
+
+  private TreeSet<WeightedWord> rankBySimilarity(String word, List<WeightedWord> expanded) {
+    double fact = (10.0 - dictionary.maxDiff) / 5.0;
+    TreeSet<WeightedWord> bySimilarity = new TreeSet<>();
+    for (WeightedWord weighted : expanded) {
+      String guess = weighted.word;
+      String lower = dictionary.toLowerCase(guess);
+      if (lower.equals(word)) {
+        bySimilarity.add(new WeightedWord(guess, weighted.score + 2000));
+        break;
+      }
+
+      int re =
+          ngram(2, word, lower, EnumSet.of(NGramOptions.ANY_MISMATCH, NGramOptions.WEIGHTED))
+              + ngram(2, lower, word, EnumSet.of(NGramOptions.ANY_MISMATCH, NGramOptions.WEIGHTED));
+
+      int score =
+          2 * lcs(word, lower)
+              - Math.abs(word.length() - lower.length())
+              + commonCharacterPositionScore(word, lower)
+              + commonPrefix(word, lower)
+              + ngram(4, word, lower, EnumSet.of(NGramOptions.ANY_MISMATCH))
+              + re
+              + (re < (word.length() + lower.length()) * fact ? -1000 : 0);
+      bySimilarity.add(new WeightedWord(guess, score));
+    }
+    return bySimilarity;
+  }
+
+  private List<String> getMostRelevantSuggestions(
+      TreeSet<WeightedWord> bySimilarity, Set<String> prevSuggestions) {
+    List<String> result = new ArrayList<>();
+    boolean hasExcellent = false;
+    for (WeightedWord weighted : bySimilarity) {
+      if (weighted.score > 1000) {
+        hasExcellent = true;
+      } else if (hasExcellent) {
+        break; // leave only excellent suggestions, if any
+      }
+
+      boolean bad = weighted.score < -100;
+      // keep the best ngram suggestions, unless in ONLYMAXDIFF mode
+      if (bad && (!result.isEmpty() || dictionary.onlyMaxDiff)) {
+        break;
+      }
+
+      if (prevSuggestions.stream().noneMatch(weighted.word::contains)
+          && result.stream().noneMatch(weighted.word::contains)) {
+        result.add(weighted.word);
+        if (result.size() > dictionary.maxNGramSuggestions) {
+          break;
+        }
+      }
+
+      if (bad) {
+        break;
+      }
+    }
+    return result;
+  }
+
+  private static int commonPrefix(String s1, String s2) {
+    int i = 0;
+    while (i < s1.length() && i < s2.length() && s1.charAt(i) == s2.charAt(i)) {
+      i++;
+    }
+    return i;
+  }
+
+  // generate an n-gram score comparing s1 and s2
+  private static int ngram(int n, String s1, String s2, EnumSet<NGramOptions> opt) {
+    int score = 0;
+    int l1 = s1.length();
+    int l2 = s2.length();
+    if (l2 == 0) {
+      return 0;
+    }
+    for (int j = 1; j <= n; j++) {
+      int ns = 0;
+      for (int i = 0; i <= (l1 - j); i++) {
+        if (s2.contains(s1.substring(i, i + j))) {
+          ns++;
+        } else if (opt.contains(NGramOptions.WEIGHTED)) {
+          ns--;
+          if (i == 0 || i == l1 - j) {
+            ns--; // side weight
+          }
+        }
+      }
+      score = score + ns;
+      if (ns < 2 && !opt.contains(NGramOptions.WEIGHTED)) {
+        break;
+      }
+    }
+
+    int ns = 0;
+    if (opt.contains(NGramOptions.LONGER_WORSE)) {
+      ns = (l2 - l1) - 2;
+    }
+    if (opt.contains(NGramOptions.ANY_MISMATCH)) {
+      ns = Math.abs(l2 - l1) - 2;
+    }
+    return score - Math.max(ns, 0);
+  }
+
+  private static int lcs(String s1, String s2) {

Review comment:
       If it's the length you need, not the subsequence, this can be optimized to store just one row/ column of memory, not the whole table?




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@lucene.apache.org
For additional commands, e-mail: issues-help@lucene.apache.org


[GitHub] [lucene-solr] dweiss commented on pull request #2320: LUCENE-9742: Hunspell: suggest dictionary entries similar to the misspelled word

Posted by GitBox <gi...@apache.org>.
dweiss commented on pull request #2320:
URL: https://github.com/apache/lucene-solr/pull/2320#issuecomment-775724487


   I don't trust the compiler that much. :) Thanks.


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@lucene.apache.org
For additional commands, e-mail: issues-help@lucene.apache.org


[GitHub] [lucene-solr] dweiss commented on a change in pull request #2320: LUCENE-9742: Hunspell: suggest dictionary entries similar to the misspelled word

Posted by GitBox <gi...@apache.org>.
dweiss commented on a change in pull request #2320:
URL: https://github.com/apache/lucene-solr/pull/2320#discussion_r572349453



##########
File path: lucene/analysis/common/src/java/org/apache/lucene/analysis/hunspell/GeneratingSuggester.java
##########
@@ -0,0 +1,321 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.lucene.analysis.hunspell;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.EnumSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.stream.Collectors;
+import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.fst.IntsRefFSTEnum;
+
+/**
+ * A class that traverses the entire dictionary and applies affix rules to check if those yield
+ * correct suggestions similar enough to the given misspelled word
+ */
+class GeneratingSuggester {
+  private static final int MAX_ROOTS = 100;
+  private static final int MAX_GUESSES = 100;
+  private final Dictionary dictionary;
+
+  GeneratingSuggester(Dictionary dictionary) {
+    this.dictionary = dictionary;
+  }
+
+  List<String> suggest(String word, WordCase originalCase, Set<String> prevSuggestions) {
+    List<WeightedWord> roots = findSimilarDictionaryEntries(word, originalCase);
+    List<WeightedWord> expanded = expandRoots(word, roots);
+    TreeSet<WeightedWord> bySimilarity = rankBySimilarity(word, expanded);
+    return getMostRelevantSuggestions(bySimilarity, prevSuggestions);
+  }
+
+  private List<WeightedWord> findSimilarDictionaryEntries(String word, WordCase originalCase) {
+    try {
+      IntsRefFSTEnum<IntsRef> fstEnum = new IntsRefFSTEnum<>(dictionary.words);
+      TreeSet<WeightedWord> roots = new TreeSet<>();
+
+      IntsRefFSTEnum.InputOutput<IntsRef> mapping;
+      while ((mapping = fstEnum.next()) != null) {
+        IntsRef key = mapping.input;
+        if (Math.abs(key.length - word.length()) > 4 || !isSuitableRoot(mapping.output)) continue;
+
+        String root = toString(key);
+        if (originalCase == WordCase.LOWER
+            && WordCase.caseOf(root) == WordCase.TITLE
+            && !dictionary.hasLanguage("de")) {
+          continue;
+        }
+
+        String lower = dictionary.toLowerCase(root);
+        int sc =
+            ngram(3, word, lower, EnumSet.of(NGramOptions.LONGER_WORSE)) + commonPrefix(word, root);
+
+        roots.add(new WeightedWord(root, sc));
+      }
+      return roots.stream().limit(MAX_ROOTS).collect(Collectors.toList());
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  private static String toString(IntsRef key) {
+    char[] chars = new char[key.length];
+    for (int i = 0; i < key.length; i++) {
+      chars[i] = (char) key.ints[i + key.offset];
+    }
+    return new String(chars);
+  }
+
+  private boolean isSuitableRoot(IntsRef forms) {
+    for (int i = 0; i < forms.length; i += dictionary.formStep()) {
+      int entryId = forms.ints[forms.offset + i];
+      if (dictionary.hasFlag(entryId, dictionary.needaffix)
+          || dictionary.hasFlag(entryId, dictionary.forbiddenword)
+          || dictionary.hasFlag(entryId, Dictionary.HIDDEN_FLAG)
+          || dictionary.hasFlag(entryId, dictionary.onlyincompound)) {
+        continue;
+      }
+      return true;
+    }
+
+    return false;
+  }
+
+  private List<WeightedWord> expandRoots(String word, List<WeightedWord> roots) {
+    int thresh = calcThreshold(word);
+
+    TreeSet<WeightedWord> expanded = new TreeSet<>();
+    for (WeightedWord weighted : roots) {
+      String guess = weighted.word;
+      String lower = dictionary.toLowerCase(guess);
+      int sc =
+          ngram(word.length(), word, lower, EnumSet.of(NGramOptions.ANY_MISMATCH))
+              + commonPrefix(word, guess);
+      if (sc > thresh) {
+        expanded.add(new WeightedWord(guess, sc));
+      }
+    }
+    return expanded.stream().limit(MAX_GUESSES).collect(Collectors.toList());
+  }
+
+  // find minimum threshold for a passable suggestion
+  // mangle original word three different ways
+  // and score them to generate a minimum acceptable score
+  private static int calcThreshold(String word) {
+    int thresh = 0;
+    for (int sp = 1; sp < 4; sp++) {
+      char[] mw = word.toCharArray();
+      for (int k = sp; k < word.length(); k += 4) {
+        mw[k] = '*';
+      }
+
+      thresh += ngram(word.length(), word, new String(mw), EnumSet.of(NGramOptions.ANY_MISMATCH));
+    }
+    return thresh / 3 - 1;
+  }
+
+  private TreeSet<WeightedWord> rankBySimilarity(String word, List<WeightedWord> expanded) {
+    double fact = (10.0 - dictionary.maxDiff) / 5.0;
+    TreeSet<WeightedWord> bySimilarity = new TreeSet<>();
+    for (WeightedWord weighted : expanded) {
+      String guess = weighted.word;
+      String lower = dictionary.toLowerCase(guess);
+      if (lower.equals(word)) {
+        bySimilarity.add(new WeightedWord(guess, weighted.score + 2000));
+        break;
+      }
+
+      int re =
+          ngram(2, word, lower, EnumSet.of(NGramOptions.ANY_MISMATCH, NGramOptions.WEIGHTED))
+              + ngram(2, lower, word, EnumSet.of(NGramOptions.ANY_MISMATCH, NGramOptions.WEIGHTED));
+
+      int score =
+          2 * lcs(word, lower)
+              - Math.abs(word.length() - lower.length())
+              + commonCharacterPositionScore(word, lower)
+              + commonPrefix(word, lower)
+              + ngram(4, word, lower, EnumSet.of(NGramOptions.ANY_MISMATCH))
+              + re
+              + (re < (word.length() + lower.length()) * fact ? -1000 : 0);
+      bySimilarity.add(new WeightedWord(guess, score));
+    }
+    return bySimilarity;
+  }
+
+  private List<String> getMostRelevantSuggestions(
+      TreeSet<WeightedWord> bySimilarity, Set<String> prevSuggestions) {
+    List<String> result = new ArrayList<>();
+    boolean hasExcellent = false;
+    for (WeightedWord weighted : bySimilarity) {
+      if (weighted.score > 1000) {
+        hasExcellent = true;
+      } else if (hasExcellent) {
+        break; // leave only excellent suggestions, if any
+      }
+
+      boolean bad = weighted.score < -100;
+      // keep the best ngram suggestions, unless in ONLYMAXDIFF mode
+      if (bad && (!result.isEmpty() || dictionary.onlyMaxDiff)) {
+        break;
+      }
+
+      if (prevSuggestions.stream().noneMatch(weighted.word::contains)
+          && result.stream().noneMatch(weighted.word::contains)) {
+        result.add(weighted.word);
+        if (result.size() > dictionary.maxNGramSuggestions) {
+          break;
+        }
+      }
+
+      if (bad) {
+        break;
+      }
+    }
+    return result;
+  }
+
+  private static int commonPrefix(String s1, String s2) {

Review comment:
       I don't know of any.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@lucene.apache.org
For additional commands, e-mail: issues-help@lucene.apache.org


[GitHub] [lucene-solr] donnerpeter commented on a change in pull request #2320: LUCENE-9742: Hunspell: suggest dictionary entries similar to the misspelled word

Posted by GitBox <gi...@apache.org>.
donnerpeter commented on a change in pull request #2320:
URL: https://github.com/apache/lucene-solr/pull/2320#discussion_r571935705



##########
File path: lucene/analysis/common/src/java/org/apache/lucene/analysis/hunspell/GeneratingSuggester.java
##########
@@ -0,0 +1,321 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.lucene.analysis.hunspell;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.EnumSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.stream.Collectors;
+import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.fst.IntsRefFSTEnum;
+
+/**
+ * A class that traverses the entire dictionary and applies affix rules to check if those yield
+ * correct suggestions similar enough to the given misspelled word
+ */
+class GeneratingSuggester {
+  private static final int MAX_ROOTS = 100;
+  private static final int MAX_GUESSES = 100;
+  private final Dictionary dictionary;
+
+  GeneratingSuggester(Dictionary dictionary) {
+    this.dictionary = dictionary;
+  }
+
+  List<String> suggest(String word, WordCase originalCase, Set<String> prevSuggestions) {
+    List<WeightedWord> roots = findSimilarDictionaryEntries(word, originalCase);
+    List<WeightedWord> expanded = expandRoots(word, roots);
+    TreeSet<WeightedWord> bySimilarity = rankBySimilarity(word, expanded);
+    return getMostRelevantSuggestions(bySimilarity, prevSuggestions);
+  }
+
+  private List<WeightedWord> findSimilarDictionaryEntries(String word, WordCase originalCase) {
+    try {
+      IntsRefFSTEnum<IntsRef> fstEnum = new IntsRefFSTEnum<>(dictionary.words);
+      TreeSet<WeightedWord> roots = new TreeSet<>();
+
+      IntsRefFSTEnum.InputOutput<IntsRef> mapping;
+      while ((mapping = fstEnum.next()) != null) {
+        IntsRef key = mapping.input;
+        if (Math.abs(key.length - word.length()) > 4 || !isSuitableRoot(mapping.output)) continue;
+
+        String root = toString(key);
+        if (originalCase == WordCase.LOWER
+            && WordCase.caseOf(root) == WordCase.TITLE
+            && !dictionary.hasLanguage("de")) {
+          continue;
+        }
+
+        String lower = dictionary.toLowerCase(root);
+        int sc =
+            ngram(3, word, lower, EnumSet.of(NGramOptions.LONGER_WORSE)) + commonPrefix(word, root);
+
+        roots.add(new WeightedWord(root, sc));
+      }
+      return roots.stream().limit(MAX_ROOTS).collect(Collectors.toList());
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  private static String toString(IntsRef key) {
+    char[] chars = new char[key.length];
+    for (int i = 0; i < key.length; i++) {
+      chars[i] = (char) key.ints[i + key.offset];
+    }
+    return new String(chars);
+  }
+
+  private boolean isSuitableRoot(IntsRef forms) {
+    for (int i = 0; i < forms.length; i += dictionary.formStep()) {
+      int entryId = forms.ints[forms.offset + i];
+      if (dictionary.hasFlag(entryId, dictionary.needaffix)
+          || dictionary.hasFlag(entryId, dictionary.forbiddenword)
+          || dictionary.hasFlag(entryId, Dictionary.HIDDEN_FLAG)
+          || dictionary.hasFlag(entryId, dictionary.onlyincompound)) {
+        continue;
+      }
+      return true;
+    }
+
+    return false;
+  }
+
+  private List<WeightedWord> expandRoots(String word, List<WeightedWord> roots) {
+    int thresh = calcThreshold(word);
+
+    TreeSet<WeightedWord> expanded = new TreeSet<>();
+    for (WeightedWord weighted : roots) {
+      String guess = weighted.word;
+      String lower = dictionary.toLowerCase(guess);
+      int sc =
+          ngram(word.length(), word, lower, EnumSet.of(NGramOptions.ANY_MISMATCH))
+              + commonPrefix(word, guess);
+      if (sc > thresh) {
+        expanded.add(new WeightedWord(guess, sc));
+      }
+    }
+    return expanded.stream().limit(MAX_GUESSES).collect(Collectors.toList());
+  }
+
+  // find minimum threshold for a passable suggestion
+  // mangle original word three different ways
+  // and score them to generate a minimum acceptable score
+  private static int calcThreshold(String word) {

Review comment:
       Most logic here is copied from Hunspell/C++, including the magic numbers




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@lucene.apache.org
For additional commands, e-mail: issues-help@lucene.apache.org


[GitHub] [lucene-solr] dweiss merged pull request #2320: LUCENE-9742: Hunspell: suggest dictionary entries similar to the misspelled word

Posted by GitBox <gi...@apache.org>.
dweiss merged pull request #2320:
URL: https://github.com/apache/lucene-solr/pull/2320


   


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@lucene.apache.org
For additional commands, e-mail: issues-help@lucene.apache.org