PhoneticEngine.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.codec.language.bm;

  18. import java.util.ArrayList;
  19. import java.util.Arrays;
  20. import java.util.Collections;
  21. import java.util.EnumMap;
  22. import java.util.HashSet;
  23. import java.util.Iterator;
  24. import java.util.LinkedHashSet;
  25. import java.util.List;
  26. import java.util.Locale;
  27. import java.util.Map;
  28. import java.util.Set;
  29. import java.util.TreeMap;

  30. import org.apache.commons.codec.language.bm.Languages.LanguageSet;
  31. import org.apache.commons.codec.language.bm.Rule.Phoneme;

  32. /**
  33.  * Converts words into potential phonetic representations.
  34.  * <p>
  35.  * This is a two-stage process. Firstly, the word is converted into a phonetic representation that takes
  36.  * into account the likely source language. Next, this phonetic representation is converted into a
  37.  * pan-European 'average' representation, allowing comparison between different versions of essentially
  38.  * the same word from different languages.
  39.  * <p>
  40.  * This class is intentionally immutable and thread-safe.
  41.  * If you wish to alter the settings for a PhoneticEngine, you
  42.  * must make a new one with the updated settings.
  43.  * <p>
  44.  * Ported from phoneticengine.php
  45.  *
  46.  * @since 1.6
  47.  * @version $Id: PhoneticEngine.java 1694610 2015-08-07 03:47:38Z ggregory $
  48.  */
  49. public class PhoneticEngine {

  50.     /**
  51.      * Utility for manipulating a set of phonemes as they are being built up. Not intended for use outside
  52.      * this package, and probably not outside the {@link PhoneticEngine} class.
  53.      *
  54.      * @since 1.6
  55.      */
  56.     static final class PhonemeBuilder {

  57.         /**
  58.          * An empty builder where all phonemes must come from some set of languages. This will contain a single
  59.          * phoneme of zero characters. This can then be appended to. This should be the only way to create a new
  60.          * phoneme from scratch.
  61.          *
  62.          * @param languages the set of languages
  63.          * @return  a new, empty phoneme builder
  64.          */
  65.         public static PhonemeBuilder empty(final Languages.LanguageSet languages) {
  66.             return new PhonemeBuilder(new Rule.Phoneme("", languages));
  67.         }

  68.         private final Set<Rule.Phoneme> phonemes;

  69.         private PhonemeBuilder(final Rule.Phoneme phoneme) {
  70.             this.phonemes = new LinkedHashSet<Rule.Phoneme>();
  71.             this.phonemes.add(phoneme);
  72.         }

  73.         private PhonemeBuilder(final Set<Rule.Phoneme> phonemes) {
  74.             this.phonemes = phonemes;
  75.         }

  76.         /**
  77.          * Creates a new phoneme builder containing all phonemes in this one extended by <code>str</code>.
  78.          *
  79.          * @param str   the characters to append to the phonemes
  80.          */
  81.         public void append(final CharSequence str) {
  82.             for (final Rule.Phoneme ph : this.phonemes) {
  83.                 ph.append(str);
  84.             }
  85.         }

  86.         /**
  87.          * Applies the given phoneme expression to all phonemes in this phoneme builder.
  88.          * <p>
  89.          * This will lengthen phonemes that have compatible language sets to the expression, and drop those that are
  90.          * incompatible.
  91.          *
  92.          * @param phonemeExpr   the expression to apply
  93.          * @param maxPhonemes   the maximum number of phonemes to build up
  94.          */
  95.         public void apply(final Rule.PhonemeExpr phonemeExpr, final int maxPhonemes) {
  96.             final Set<Rule.Phoneme> newPhonemes = new LinkedHashSet<Rule.Phoneme>(maxPhonemes);

  97.             EXPR: for (final Rule.Phoneme left : this.phonemes) {
  98.                 for (final Rule.Phoneme right : phonemeExpr.getPhonemes()) {
  99.                     final LanguageSet languages = left.getLanguages().restrictTo(right.getLanguages());
  100.                     if (!languages.isEmpty()) {
  101.                         final Rule.Phoneme join = new Phoneme(left, right, languages);
  102.                         if (newPhonemes.size() < maxPhonemes) {
  103.                             newPhonemes.add(join);
  104.                             if (newPhonemes.size() >= maxPhonemes) {
  105.                                 break EXPR;
  106.                             }
  107.                         }
  108.                     }
  109.                 }
  110.             }

  111.             this.phonemes.clear();
  112.             this.phonemes.addAll(newPhonemes);
  113.         }

  114.         /**
  115.          * Gets underlying phoneme set. Please don't mutate.
  116.          *
  117.          * @return  the phoneme set
  118.          */
  119.         public Set<Rule.Phoneme> getPhonemes() {
  120.             return this.phonemes;
  121.         }

  122.         /**
  123.          * Stringifies the phoneme set. This produces a single string of the strings of each phoneme,
  124.          * joined with a pipe. This is explicitly provided in place of toString as it is a potentially
  125.          * expensive operation, which should be avoided when debugging.
  126.          *
  127.          * @return  the stringified phoneme set
  128.          */
  129.         public String makeString() {
  130.             final StringBuilder sb = new StringBuilder();

  131.             for (final Rule.Phoneme ph : this.phonemes) {
  132.                 if (sb.length() > 0) {
  133.                     sb.append("|");
  134.                 }
  135.                 sb.append(ph.getPhonemeText());
  136.             }

  137.             return sb.toString();
  138.         }
  139.     }

  140.     /**
  141.      * A function closure capturing the application of a list of rules to an input sequence at a particular offset.
  142.      * After invocation, the values <code>i</code> and <code>found</code> are updated. <code>i</code> points to the
  143.      * index of the next char in <code>input</code> that must be processed next (the input up to that index having been
  144.      * processed already), and <code>found</code> indicates if a matching rule was found or not. In the case where a
  145.      * matching rule was found, <code>phonemeBuilder</code> is replaced with a new builder containing the phonemes
  146.      * updated by the matching rule.
  147.      *
  148.      * Although this class is not thread-safe (it has mutable unprotected fields), it is not shared between threads
  149.      * as it is constructed as needed by the calling methods.
  150.      * @since 1.6
  151.      */
  152.     private static final class RulesApplication {
  153.         private final Map<String, List<Rule>> finalRules;
  154.         private final CharSequence input;

  155.         private final PhonemeBuilder phonemeBuilder;
  156.         private int i;
  157.         private final int maxPhonemes;
  158.         private boolean found;

  159.         public RulesApplication(final Map<String, List<Rule>> finalRules, final CharSequence input,
  160.                                 final PhonemeBuilder phonemeBuilder, final int i, final int maxPhonemes) {
  161.             if (finalRules == null) {
  162.                 throw new NullPointerException("The finalRules argument must not be null");
  163.             }
  164.             this.finalRules = finalRules;
  165.             this.phonemeBuilder = phonemeBuilder;
  166.             this.input = input;
  167.             this.i = i;
  168.             this.maxPhonemes = maxPhonemes;
  169.         }

  170.         public int getI() {
  171.             return this.i;
  172.         }

  173.         public PhonemeBuilder getPhonemeBuilder() {
  174.             return this.phonemeBuilder;
  175.         }

  176.         /**
  177.          * Invokes the rules. Loops over the rules list, stopping at the first one that has a matching context
  178.          * and pattern. Then applies this rule to the phoneme builder to produce updated phonemes. If there was no
  179.          * match, <code>i</code> is advanced one and the character is silently dropped from the phonetic spelling.
  180.          *
  181.          * @return <code>this</code>
  182.          */
  183.         public RulesApplication invoke() {
  184.             this.found = false;
  185.             int patternLength = 1;
  186.             final List<Rule> rules = this.finalRules.get(input.subSequence(i, i+patternLength));
  187.             if (rules != null) {
  188.                 for (final Rule rule : rules) {
  189.                     final String pattern = rule.getPattern();
  190.                     patternLength = pattern.length();
  191.                     if (rule.patternAndContextMatches(this.input, this.i)) {
  192.                         this.phonemeBuilder.apply(rule.getPhoneme(), maxPhonemes);
  193.                         this.found = true;
  194.                         break;
  195.                     }
  196.                 }
  197.             }

  198.             if (!this.found) {
  199.                 patternLength = 1;
  200.             }

  201.             this.i += patternLength;
  202.             return this;
  203.         }

  204.         public boolean isFound() {
  205.             return this.found;
  206.         }
  207.     }

  208.     private static final Map<NameType, Set<String>> NAME_PREFIXES = new EnumMap<NameType, Set<String>>(NameType.class);

  209.     static {
  210.         NAME_PREFIXES.put(NameType.ASHKENAZI,
  211.                 Collections.unmodifiableSet(
  212.                         new HashSet<String>(Arrays.asList("bar", "ben", "da", "de", "van", "von"))));
  213.         NAME_PREFIXES.put(NameType.SEPHARDIC,
  214.                 Collections.unmodifiableSet(
  215.                         new HashSet<String>(Arrays.asList("al", "el", "da", "dal", "de", "del", "dela", "de la",
  216.                                                           "della", "des", "di", "do", "dos", "du", "van", "von"))));
  217.         NAME_PREFIXES.put(NameType.GENERIC,
  218.                 Collections.unmodifiableSet(
  219.                         new HashSet<String>(Arrays.asList("da", "dal", "de", "del", "dela", "de la", "della",
  220.                                                           "des", "di", "do", "dos", "du", "van", "von"))));
  221.     }

  222.     /**
  223.      * Joins some strings with an internal separator.
  224.      * @param strings   Strings to join
  225.      * @param sep       String to separate them with
  226.      * @return a single String consisting of each element of <code>strings</code> interleaved by <code>sep</code>
  227.      */
  228.     private static String join(final Iterable<String> strings, final String sep) {
  229.         final StringBuilder sb = new StringBuilder();
  230.         final Iterator<String> si = strings.iterator();
  231.         if (si.hasNext()) {
  232.             sb.append(si.next());
  233.         }
  234.         while (si.hasNext()) {
  235.             sb.append(sep).append(si.next());
  236.         }

  237.         return sb.toString();
  238.     }

  239.     private static final int DEFAULT_MAX_PHONEMES = 20;

  240.     private final Lang lang;

  241.     private final NameType nameType;

  242.     private final RuleType ruleType;

  243.     private final boolean concat;

  244.     private final int maxPhonemes;

  245.     /**
  246.      * Generates a new, fully-configured phonetic engine.
  247.      *
  248.      * @param nameType
  249.      *            the type of names it will use
  250.      * @param ruleType
  251.      *            the type of rules it will apply
  252.      * @param concat
  253.      *            if it will concatenate multiple encodings
  254.      */
  255.     public PhoneticEngine(final NameType nameType, final RuleType ruleType, final boolean concat) {
  256.         this(nameType, ruleType, concat, DEFAULT_MAX_PHONEMES);
  257.     }

  258.     /**
  259.      * Generates a new, fully-configured phonetic engine.
  260.      *
  261.      * @param nameType
  262.      *            the type of names it will use
  263.      * @param ruleType
  264.      *            the type of rules it will apply
  265.      * @param concat
  266.      *            if it will concatenate multiple encodings
  267.      * @param maxPhonemes
  268.      *            the maximum number of phonemes that will be handled
  269.      * @since 1.7
  270.      */
  271.     public PhoneticEngine(final NameType nameType, final RuleType ruleType, final boolean concat,
  272.                           final int maxPhonemes) {
  273.         if (ruleType == RuleType.RULES) {
  274.             throw new IllegalArgumentException("ruleType must not be " + RuleType.RULES);
  275.         }
  276.         this.nameType = nameType;
  277.         this.ruleType = ruleType;
  278.         this.concat = concat;
  279.         this.lang = Lang.instance(nameType);
  280.         this.maxPhonemes = maxPhonemes;
  281.     }

  282.     /**
  283.      * Applies the final rules to convert from a language-specific phonetic representation to a
  284.      * language-independent representation.
  285.      *
  286.      * @param phonemeBuilder the current phonemes
  287.      * @param finalRules the final rules to apply
  288.      * @return the resulting phonemes
  289.      */
  290.     private PhonemeBuilder applyFinalRules(final PhonemeBuilder phonemeBuilder,
  291.                                            final Map<String, List<Rule>> finalRules) {
  292.         if (finalRules == null) {
  293.             throw new NullPointerException("finalRules can not be null");
  294.         }
  295.         if (finalRules.isEmpty()) {
  296.             return phonemeBuilder;
  297.         }

  298.         final Map<Rule.Phoneme, Rule.Phoneme> phonemes =
  299.             new TreeMap<Rule.Phoneme, Rule.Phoneme>(Rule.Phoneme.COMPARATOR);

  300.         for (final Rule.Phoneme phoneme : phonemeBuilder.getPhonemes()) {
  301.             PhonemeBuilder subBuilder = PhonemeBuilder.empty(phoneme.getLanguages());
  302.             final String phonemeText = phoneme.getPhonemeText().toString();

  303.             for (int i = 0; i < phonemeText.length();) {
  304.                 final RulesApplication rulesApplication =
  305.                         new RulesApplication(finalRules, phonemeText, subBuilder, i, maxPhonemes).invoke();
  306.                 final boolean found = rulesApplication.isFound();
  307.                 subBuilder = rulesApplication.getPhonemeBuilder();

  308.                 if (!found) {
  309.                     // not found, appending as-is
  310.                     subBuilder.append(phonemeText.subSequence(i, i + 1));
  311.                 }

  312.                 i = rulesApplication.getI();
  313.             }

  314.             // the phonemes map orders the phonemes only based on their text, but ignores the language set
  315.             // when adding new phonemes, check for equal phonemes and merge their language set, otherwise
  316.             // phonemes with the same text but different language set get lost
  317.             for (final Rule.Phoneme newPhoneme : subBuilder.getPhonemes()) {
  318.                 if (phonemes.containsKey(newPhoneme)) {
  319.                     final Rule.Phoneme oldPhoneme = phonemes.remove(newPhoneme);
  320.                     final Rule.Phoneme mergedPhoneme = oldPhoneme.mergeWithLanguage(newPhoneme.getLanguages());
  321.                     phonemes.put(mergedPhoneme, mergedPhoneme);
  322.                 } else {
  323.                     phonemes.put(newPhoneme, newPhoneme);
  324.                 }
  325.             }
  326.         }

  327.         return new PhonemeBuilder(phonemes.keySet());
  328.     }

  329.     /**
  330.      * Encodes a string to its phonetic representation.
  331.      *
  332.      * @param input
  333.      *            the String to encode
  334.      * @return the encoding of the input
  335.      */
  336.     public String encode(final String input) {
  337.         final Languages.LanguageSet languageSet = this.lang.guessLanguages(input);
  338.         return encode(input, languageSet);
  339.     }

  340.     /**
  341.      * Encodes an input string into an output phonetic representation, given a set of possible origin languages.
  342.      *
  343.      * @param input
  344.      *            String to phoneticise; a String with dashes or spaces separating each word
  345.      * @param languageSet
  346.      *            set of possible origin languages
  347.      * @return a phonetic representation of the input; a String containing '-'-separated phonetic representations of the
  348.      *         input
  349.      */
  350.     public String encode(String input, final Languages.LanguageSet languageSet) {
  351.         final Map<String, List<Rule>> rules = Rule.getInstanceMap(this.nameType, RuleType.RULES, languageSet);
  352.         // rules common across many (all) languages
  353.         final Map<String, List<Rule>> finalRules1 = Rule.getInstanceMap(this.nameType, this.ruleType, "common");
  354.         // rules that apply to a specific language that may be ambiguous or wrong if applied to other languages
  355.         final Map<String, List<Rule>> finalRules2 = Rule.getInstanceMap(this.nameType, this.ruleType, languageSet);

  356.         // tidy the input
  357.         // lower case is a locale-dependent operation
  358.         input = input.toLowerCase(Locale.ENGLISH).replace('-', ' ').trim();

  359.         if (this.nameType == NameType.GENERIC) {
  360.             if (input.length() >= 2 && input.substring(0, 2).equals("d'")) { // check for d'
  361.                 final String remainder = input.substring(2);
  362.                 final String combined = "d" + remainder;
  363.                 return "(" + encode(remainder) + ")-(" + encode(combined) + ")";
  364.             }
  365.             for (final String l : NAME_PREFIXES.get(this.nameType)) {
  366.                 // handle generic prefixes
  367.                 if (input.startsWith(l + " ")) {
  368.                     // check for any prefix in the words list
  369.                     final String remainder = input.substring(l.length() + 1); // input without the prefix
  370.                     final String combined = l + remainder; // input with prefix without space
  371.                     return "(" + encode(remainder) + ")-(" + encode(combined) + ")";
  372.                 }
  373.             }
  374.         }

  375.         final List<String> words = Arrays.asList(input.split("\\s+"));
  376.         final List<String> words2 = new ArrayList<String>();

  377.         // special-case handling of word prefixes based upon the name type
  378.         switch (this.nameType) {
  379.         case SEPHARDIC:
  380.             for (final String aWord : words) {
  381.                 final String[] parts = aWord.split("'");
  382.                 final String lastPart = parts[parts.length - 1];
  383.                 words2.add(lastPart);
  384.             }
  385.             words2.removeAll(NAME_PREFIXES.get(this.nameType));
  386.             break;
  387.         case ASHKENAZI:
  388.             words2.addAll(words);
  389.             words2.removeAll(NAME_PREFIXES.get(this.nameType));
  390.             break;
  391.         case GENERIC:
  392.             words2.addAll(words);
  393.             break;
  394.         default:
  395.             throw new IllegalStateException("Unreachable case: " + this.nameType);
  396.         }

  397.         if (this.concat) {
  398.             // concat mode enabled
  399.             input = join(words2, " ");
  400.         } else if (words2.size() == 1) {
  401.             // not a multi-word name
  402.             input = words.iterator().next();
  403.         } else {
  404.             // encode each word in a multi-word name separately (normally used for approx matches)
  405.             final StringBuilder result = new StringBuilder();
  406.             for (final String word : words2) {
  407.                 result.append("-").append(encode(word));
  408.             }
  409.             // return the result without the leading "-"
  410.             return result.substring(1);
  411.         }

  412.         PhonemeBuilder phonemeBuilder = PhonemeBuilder.empty(languageSet);

  413.         // loop over each char in the input - we will handle the increment manually
  414.         for (int i = 0; i < input.length();) {
  415.             final RulesApplication rulesApplication =
  416.                     new RulesApplication(rules, input, phonemeBuilder, i, maxPhonemes).invoke();
  417.             i = rulesApplication.getI();
  418.             phonemeBuilder = rulesApplication.getPhonemeBuilder();
  419.         }

  420.         // Apply the general rules
  421.         phonemeBuilder = applyFinalRules(phonemeBuilder, finalRules1);
  422.         // Apply the language-specific rules
  423.         phonemeBuilder = applyFinalRules(phonemeBuilder, finalRules2);

  424.         return phonemeBuilder.makeString();
  425.     }

  426.     /**
  427.      * Gets the Lang language guessing rules being used.
  428.      *
  429.      * @return the Lang in use
  430.      */
  431.     public Lang getLang() {
  432.         return this.lang;
  433.     }

  434.     /**
  435.      * Gets the NameType being used.
  436.      *
  437.      * @return the NameType in use
  438.      */
  439.     public NameType getNameType() {
  440.         return this.nameType;
  441.     }

  442.     /**
  443.      * Gets the RuleType being used.
  444.      *
  445.      * @return the RuleType in use
  446.      */
  447.     public RuleType getRuleType() {
  448.         return this.ruleType;
  449.     }

  450.     /**
  451.      * Gets if multiple phonetic encodings are concatenated or if just the first one is kept.
  452.      *
  453.      * @return true if multiple phonetic encodings are returned, false if just the first is
  454.      */
  455.     public boolean isConcat() {
  456.         return this.concat;
  457.     }

  458.     /**
  459.      * Gets the maximum number of phonemes the engine will calculate for a given input.
  460.      *
  461.      * @return the maximum number of phonemes
  462.      * @since 1.7
  463.      */
  464.     public int getMaxPhonemes() {
  465.         return this.maxPhonemes;
  466.     }
  467. }