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