1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.codec.language.bm;
19
20 import java.util.ArrayList;
21 import java.util.Arrays;
22 import java.util.Collections;
23 import java.util.EnumMap;
24 import java.util.HashSet;
25 import java.util.LinkedHashSet;
26 import java.util.List;
27 import java.util.Locale;
28 import java.util.Map;
29 import java.util.Objects;
30 import java.util.Set;
31 import java.util.TreeMap;
32 import java.util.stream.Collectors;
33
34 import org.apache.commons.codec.language.bm.Languages.LanguageSet;
35 import org.apache.commons.codec.language.bm.Rule.Phoneme;
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56 public class PhoneticEngine {
57
58
59
60
61
62
63
64 static final class PhonemeBuilder {
65
66
67
68
69
70
71
72
73
74 public static PhonemeBuilder empty(final Languages.LanguageSet languages) {
75 return new PhonemeBuilder(new Rule.Phoneme("", languages));
76 }
77
78 private final Set<Rule.Phoneme> phonemes;
79
80 private PhonemeBuilder(final Rule.Phoneme phoneme) {
81 this.phonemes = new LinkedHashSet<>();
82 this.phonemes.add(phoneme);
83 }
84
85 private PhonemeBuilder(final Set<Rule.Phoneme> phonemes) {
86 this.phonemes = phonemes;
87 }
88
89
90
91
92
93
94 public void append(final CharSequence str) {
95 phonemes.forEach(ph -> ph.append(str));
96 }
97
98
99
100
101
102
103
104
105
106
107
108 public void apply(final Rule.PhonemeExpr phonemeExpr, final int maxPhonemes) {
109 final Set<Rule.Phoneme> newPhonemes = new LinkedHashSet<>(Math.min(phonemes.size() * phonemeExpr.size(), maxPhonemes));
110 EXPR: for (final Rule.Phoneme left : phonemes) {
111 for (final Rule.Phoneme right : phonemeExpr.getPhonemes()) {
112 final LanguageSet languages = left.getLanguages().restrictTo(right.getLanguages());
113 if (!languages.isEmpty()) {
114 final Rule.Phoneme join = new Phoneme(left, right, languages);
115 if (newPhonemes.size() < maxPhonemes) {
116 newPhonemes.add(join);
117 if (newPhonemes.size() >= maxPhonemes) {
118 break EXPR;
119 }
120 }
121 }
122 }
123 }
124 phonemes.clear();
125 phonemes.addAll(newPhonemes);
126 }
127
128
129
130
131
132
133 public Set<Rule.Phoneme> getPhonemes() {
134 return phonemes;
135 }
136
137
138
139
140
141
142
143
144 public String makeString() {
145 return phonemes.stream().map(Rule.Phoneme::getPhonemeText).collect(Collectors.joining("|"));
146 }
147 }
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163 private static final class RulesApplication {
164
165 private final Map<String, List<Rule>> finalRules;
166 private final CharSequence input;
167 private final PhonemeBuilder phonemeBuilder;
168 private int i;
169 private final int maxPhonemes;
170 private boolean found;
171
172 public RulesApplication(final Map<String, List<Rule>> finalRules, final CharSequence input, final PhonemeBuilder phonemeBuilder, final int i,
173 final int maxPhonemes) {
174 Objects.requireNonNull(finalRules, "finalRules");
175 this.finalRules = finalRules;
176 this.phonemeBuilder = phonemeBuilder;
177 this.input = input;
178 this.i = i;
179 this.maxPhonemes = maxPhonemes;
180 }
181
182 public int getI() {
183 return i;
184 }
185
186 public PhonemeBuilder getPhonemeBuilder() {
187 return phonemeBuilder;
188 }
189
190
191
192
193
194
195
196
197 public RulesApplication invoke() {
198 found = false;
199 int patternLength = 1;
200 final List<Rule> rules = finalRules.get(input.subSequence(i, i + patternLength));
201 if (rules != null) {
202 for (final Rule rule : rules) {
203 final String pattern = rule.getPattern();
204 patternLength = pattern.length();
205 if (rule.patternAndContextMatches(input, i)) {
206 phonemeBuilder.apply(rule.getPhoneme(), maxPhonemes);
207 found = true;
208 break;
209 }
210 }
211 }
212
213 if (!found) {
214 patternLength = 1;
215 }
216
217 i += patternLength;
218 return this;
219 }
220
221 public boolean isFound() {
222 return found;
223 }
224 }
225
226 private static final int DEFAULT_MAX_PHONEMES = 20;
227
228 private static final Map<NameType, Set<String>> NAME_PREFIXES = new EnumMap<>(NameType.class);
229
230 static {
231 NAME_PREFIXES.put(NameType.ASHKENAZI,
232 Collections.unmodifiableSet(
233 new HashSet<>(Arrays.asList("bar", "ben", "da", "de", "van", "von"))));
234 NAME_PREFIXES.put(NameType.SEPHARDIC,
235 Collections.unmodifiableSet(
236 new HashSet<>(Arrays.asList("al", "el", "da", "dal", "de", "del", "dela", "de la",
237 "della", "des", "di", "do", "dos", "du", "van", "von"))));
238 NAME_PREFIXES.put(NameType.GENERIC,
239 Collections.unmodifiableSet(
240 new HashSet<>(Arrays.asList("da", "dal", "de", "del", "dela", "de la", "della",
241 "des", "di", "do", "dos", "du", "van", "von"))));
242 }
243
244
245
246
247
248
249
250
251 private static String join(final List<String> strings, final String sep) {
252 return strings.stream().collect(Collectors.joining(sep));
253 }
254
255 private final Lang lang;
256
257 private final NameType nameType;
258
259 private final RuleType ruleType;
260
261 private final boolean concat;
262
263 private final int maxPhonemes;
264
265
266
267
268
269
270
271
272
273
274
275 public PhoneticEngine(final NameType nameType, final RuleType ruleType, final boolean concatenate) {
276 this(nameType, ruleType, concatenate, DEFAULT_MAX_PHONEMES);
277 }
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292 public PhoneticEngine(final NameType nameType, final RuleType ruleType, final boolean concatenate, final int maxPhonemes) {
293 if (ruleType == RuleType.RULES) {
294 throw new IllegalArgumentException("ruleType must not be " + RuleType.RULES);
295 }
296 this.nameType = nameType;
297 this.ruleType = ruleType;
298 this.concat = concatenate;
299 this.lang = Lang.instance(nameType);
300 this.maxPhonemes = maxPhonemes;
301 }
302
303
304
305
306
307
308
309
310
311 private PhonemeBuilder applyFinalRules(final PhonemeBuilder phonemeBuilder,
312 final Map<String, List<Rule>> finalRules) {
313 Objects.requireNonNull(finalRules, "finalRules");
314 if (finalRules.isEmpty()) {
315 return phonemeBuilder;
316 }
317
318 final Map<Rule.Phoneme, Rule.Phoneme> phonemes = new TreeMap<>(Rule.Phoneme.COMPARATOR);
319
320 phonemeBuilder.getPhonemes().forEach(phoneme -> {
321 PhonemeBuilder subBuilder = PhonemeBuilder.empty(phoneme.getLanguages());
322 final String phonemeText = phoneme.getPhonemeText().toString();
323
324 for (int i = 0; i < phonemeText.length();) {
325 final RulesApplication rulesApplication = new RulesApplication(finalRules, phonemeText, subBuilder, i, maxPhonemes).invoke();
326 final boolean found = rulesApplication.isFound();
327 subBuilder = rulesApplication.getPhonemeBuilder();
328
329 if (!found) {
330
331 subBuilder.append(phonemeText.subSequence(i, i + 1));
332 }
333
334 i = rulesApplication.getI();
335 }
336
337
338
339
340 subBuilder.getPhonemes().forEach(newPhoneme -> {
341 if (phonemes.containsKey(newPhoneme)) {
342 final Rule.Phoneme oldPhoneme = phonemes.remove(newPhoneme);
343 final Rule.Phoneme mergedPhoneme = oldPhoneme.mergeWithLanguage(newPhoneme.getLanguages());
344 phonemes.put(mergedPhoneme, mergedPhoneme);
345 } else {
346 phonemes.put(newPhoneme, newPhoneme);
347 }
348 });
349 });
350
351 return new PhonemeBuilder(phonemes.keySet());
352 }
353
354
355
356
357
358
359
360
361 public String encode(final String input) {
362 final Languages.LanguageSet languageSet = this.lang.guessLanguages(input);
363 return encode(input, languageSet);
364 }
365
366
367
368
369
370
371
372
373
374
375
376 public String encode(String input, final Languages.LanguageSet languageSet) {
377 final Map<String, List<Rule>> rules = Rule.getInstanceMap(this.nameType, RuleType.RULES, languageSet);
378
379 final Map<String, List<Rule>> finalRules1 = Rule.getInstanceMap(this.nameType, this.ruleType, "common");
380
381 final Map<String, List<Rule>> finalRules2 = Rule.getInstanceMap(this.nameType, this.ruleType, languageSet);
382
383
384
385 input = input.toLowerCase(Locale.ENGLISH).replace('-', ' ').trim();
386
387 if (this.nameType == NameType.GENERIC) {
388 if (input.startsWith("d'")) {
389 final String remainder = input.substring(2);
390 final String combined = "d" + remainder;
391 return "(" + encode(remainder) + ")-(" + encode(combined) + ")";
392 }
393 for (final String l : NAME_PREFIXES.get(this.nameType)) {
394
395 if (input.startsWith(l + " ")) {
396
397 final String remainder = input.substring(l.length() + 1);
398 final String combined = l + remainder;
399 return "(" + encode(remainder) + ")-(" + encode(combined) + ")";
400 }
401 }
402 }
403
404 final List<String> words = Arrays.asList(input.split("\\s+"));
405 final List<String> words2 = new ArrayList<>();
406
407
408 switch (this.nameType) {
409 case SEPHARDIC:
410 words.forEach(aWord -> {
411 final String[] parts = aWord.split("'", -1);
412 words2.add(parts[parts.length - 1]);
413 });
414 words2.removeAll(NAME_PREFIXES.get(this.nameType));
415 break;
416 case ASHKENAZI:
417 words2.addAll(words);
418 words2.removeAll(NAME_PREFIXES.get(this.nameType));
419 break;
420 case GENERIC:
421 words2.addAll(words);
422 break;
423 default:
424 throw new IllegalStateException("Unreachable case: " + this.nameType);
425 }
426
427 if (this.concat) {
428
429 input = join(words2, " ");
430 } else if (words2.size() == 1) {
431
432 input = words.iterator().next();
433 } else if (!words2.isEmpty()) {
434
435 final StringBuilder result = new StringBuilder();
436 words2.forEach(word -> result.append("-").append(encode(word)));
437
438 return result.substring(1);
439 }
440
441 PhonemeBuilder phonemeBuilder = PhonemeBuilder.empty(languageSet);
442
443
444 for (int i = 0; i < input.length();) {
445 final RulesApplication rulesApplication =
446 new RulesApplication(rules, input, phonemeBuilder, i, maxPhonemes).invoke();
447 i = rulesApplication.getI();
448 phonemeBuilder = rulesApplication.getPhonemeBuilder();
449 }
450
451
452 phonemeBuilder = applyFinalRules(phonemeBuilder, finalRules1);
453
454 phonemeBuilder = applyFinalRules(phonemeBuilder, finalRules2);
455
456 return phonemeBuilder.makeString();
457 }
458
459
460
461
462
463
464 public Lang getLang() {
465 return this.lang;
466 }
467
468
469
470
471
472
473
474 public int getMaxPhonemes() {
475 return this.maxPhonemes;
476 }
477
478
479
480
481
482
483 public NameType getNameType() {
484 return this.nameType;
485 }
486
487
488
489
490
491
492 public RuleType getRuleType() {
493 return this.ruleType;
494 }
495
496
497
498
499
500
501 public boolean isConcat() {
502 return this.concat;
503 }
504 }