-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
TokenInflectionAgreementRule.java
332 lines (251 loc) · 11.6 KB
/
TokenInflectionAgreementRule.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
/* LanguageTool, a natural language style checker
* Copyright (C) 2013 Andriy Rysin
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.rules.uk;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.ResourceBundle;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.languagetool.AnalyzedSentence;
import org.languagetool.AnalyzedToken;
import org.languagetool.AnalyzedTokenReadings;
import org.languagetool.JLanguageTool;
import org.languagetool.language.Ukrainian;
import org.languagetool.rules.Categories;
import org.languagetool.rules.Rule;
import org.languagetool.rules.RuleMatch;
import org.languagetool.rules.uk.InflectionHelper.Inflection;
import org.languagetool.synthesis.Synthesizer;
import org.languagetool.tagging.uk.PosTagHelper;
/**
* A rule that checks if adjective and following noun agree on gender and inflection
*
* @author Andriy Rysin
*/
public class TokenInflectionAgreementRule extends Rule {
static final Pattern ADJ_INFLECTION_PATTERN = Pattern.compile(":([mfnp]):(v_...)(:r(in)?anim)?");
static final Pattern NOUN_INFLECTION_PATTERN = Pattern.compile("(?::((?:[iu]n)?anim))?:([mfnps]):(v_...)");
static boolean DEBUG = Boolean.getBoolean("org.languagetool.rules.uk.TokenInflectionAgreementRule.debug");
// private static final Logger logger = LoggerFactory.getLogger(TokenInflectionAgreementRule.class);
private static final String NO_VIDMINOK_SUBSTR = ":nv";
private final Ukrainian ukrainian = new Ukrainian();
public TokenInflectionAgreementRule(ResourceBundle messages) throws IOException {
super.setCategory(Categories.MISC.getCategory(messages));
// setDefaultOff();
}
@Override
public final String getId() {
return "UK_ADJ_NOUN_INFLECTION_AGREEMENT";
}
@Override
public String getDescription() {
return "Узгодження відмінків, роду і числа прикметника та іменника";
}
public String getShort() {
return "Узгодження прикметника та іменника";
}
@Override
public final RuleMatch[] match(AnalyzedSentence text) {
List<RuleMatch> ruleMatches = new ArrayList<>();
AnalyzedTokenReadings[] tokens = text.getTokensWithoutWhitespace();
List<AnalyzedToken> adjTokenReadings = new ArrayList<>();
AnalyzedTokenReadings adjAnalyzedTokenReadings = null;
for (int i = 1; i < tokens.length; i++) {
AnalyzedTokenReadings tokenReadings = tokens[i];
String posTag0 = tokenReadings.getAnalyzedToken(0).getPOSTag();
if( posTag0 == null ) {
// || posTag0.equals(JLanguageTool.SENTENCE_START_TAGNAME) ){
adjTokenReadings.clear();
continue;
}
// grab initial adjective inflections
if( adjTokenReadings.isEmpty() ) {
// no need to start checking on last token or if no noun
if( i == tokens.length - 1 )
continue;
//TODO: nv still can be wrong if :np/:ns is present to it's not much gain for lots of work
if( PosTagHelper.hasPosTagPart(tokens[i], ":nv")
//TODO: turn back on when we can handle pron
|| PosTagHelper.hasPosTagPart(tokens[i], "&pron")
|| PosTagHelper.hasPosTagPart(tokens[i], "<") )
continue;
if( ! PosTagHelper.hasPosTagPart(tokens[i+1], "noun:")
|| PosTagHelper.hasPosTagPart(tokens[i+1], ":nv")
|| PosTagHelper.hasPosTagPart(tokens[i+1], "&pron")
|| PosTagHelper.hasPosTagPart(tokens[i+1], "<") )
continue;
//TODO: TEMP?
if( LemmaHelper.hasLemma(tokens[i], Arrays.asList("червоний", "правий", "місцевий", "найсильніший", "найкращі"), ":p:")
|| LemmaHelper.hasLemma(tokens[i], Arrays.asList("новенький", "головний", "вибраний", "більший", "побачений", "подібний"), ":n:")
|| LemmaHelper.hasLemma(tokens[i], Arrays.asList("державний"), ":f:") ) {
adjTokenReadings.clear();
break;
}
for (AnalyzedToken token: tokenReadings) {
String adjPosTag = token.getPOSTag();
if( adjPosTag == null ) { // can happen for words with \u0301 or \u00AD
continue;
}
if( adjPosTag.startsWith("adj") ) {
adjTokenReadings.add(token);
adjAnalyzedTokenReadings = tokenReadings;
}
else {
adjTokenReadings.clear();
break;
}
}
continue;
}
List<AnalyzedToken> slaveTokenReadings = new ArrayList<>();
for (AnalyzedToken token: tokenReadings) {
String nounPosTag = token.getPOSTag();
if( nounPosTag == null ) { // can happen for words with \u0301 or \u00AD
continue;
}
if( nounPosTag.startsWith("noun")
&& ! nounPosTag.contains(NO_VIDMINOK_SUBSTR) ) {
slaveTokenReadings.add(token);
}
else if ( nounPosTag.equals(JLanguageTool.SENTENCE_END_TAGNAME)
|| nounPosTag.equals(JLanguageTool.PARAGRAPH_END_TAGNAME) ) {
continue;
}
else {
slaveTokenReadings.clear();
break;
}
}
// no slave token - restart
if( slaveTokenReadings.isEmpty() ) {
adjTokenReadings.clear();
continue;
}
if( DEBUG ) {
System.err.println(MessageFormat.format("=== Checking:\n\t{}\n\t{}", adjTokenReadings, slaveTokenReadings));
}
// perform the check
List<InflectionHelper.Inflection> masterInflections = InflectionHelper.getAdjInflections(adjTokenReadings);
List<InflectionHelper.Inflection> slaveInflections = InflectionHelper.getNounInflections(slaveTokenReadings);
if( Collections.disjoint(masterInflections, slaveInflections) ) {
if( TokenInflectionExceptionHelper.isException(tokens, i, masterInflections, slaveInflections, adjTokenReadings, slaveTokenReadings) ) {
adjTokenReadings.clear();
continue;
}
if( DEBUG ) {
System.err.println(MessageFormat.format("=== Found:\n\t{}\n\t",
adjAnalyzedTokenReadings.getToken() + ": " + masterInflections + " // " + adjAnalyzedTokenReadings,
slaveTokenReadings.get(0).getToken() + ": " + slaveInflections+ " // " + slaveTokenReadings));
}
String msg = String.format("Потенційна помилка: прикметник не узгоджений з іменником: \"%s\": [%s] і \"%s\": [%s]",
adjTokenReadings.get(0).getToken(), formatInflections(masterInflections, true),
slaveTokenReadings.get(0).getToken(), formatInflections(slaveInflections, false));
if( PosTagHelper.hasPosTagPart(adjTokenReadings, ":m:v_rod")
&& tokens[i].getToken().matches(".*[ую]")
&& PosTagHelper.hasPosTag(slaveTokenReadings, "noun.*:m:v_dav.*") ) {
msg += ". Можливо вжито неунормований родовий відмінок ч.р. з закінченням -у/ю замість -а/я?";
}
RuleMatch potentialRuleMatch = new RuleMatch(this, adjAnalyzedTokenReadings.getStartPos(), tokenReadings.getEndPos(), msg, getShort());
Synthesizer ukrainianSynthesizer = ukrainian.getSynthesizer();
List<String> suggestions = new ArrayList<>();
try {
for (Inflection adjInflection : masterInflections) {
String genderTag = ":"+adjInflection.gender+":";
String vidmTag = adjInflection._case;
if( ! adjInflection._case.equals("v_kly")
&& (adjInflection.gender.equals("p")
|| PosTagHelper.hasPosTagPart(slaveTokenReadings, genderTag)) ) {
for(AnalyzedToken nounToken: slaveTokenReadings) {
if( adjInflection.animMatters() ) {
if( ! nounToken.getPOSTag().contains(":" + adjInflection.animTag) )
continue;
}
String newNounPosTag = nounToken.getPOSTag().replaceFirst(":.:v_...", genderTag + vidmTag);
String[] synthesized = ukrainianSynthesizer.synthesize(nounToken, newNounPosTag, false);
for (String s : synthesized) {
String suggestion = adjAnalyzedTokenReadings.getToken() + " " + s;
if( ! suggestions.contains(suggestion) ) {
suggestions.add(suggestion);
}
}
}
}
}
for (Inflection nounInflection : slaveInflections) {
String genderTag = ":"+nounInflection.gender+":";
String vidmTag = nounInflection._case;
if( nounInflection.animMatters() ) {
vidmTag += ":r" + nounInflection.animTag;
}
for(AnalyzedToken adjToken: adjTokenReadings) {
String newAdjTag = adjToken.getPOSTag().replaceFirst(":.:v_...(:r(in)?anim)?", genderTag + vidmTag);
String[] synthesized = ukrainianSynthesizer.synthesize(adjToken, newAdjTag, false);
for (String s : synthesized) {
String suggestion = s + " " + tokenReadings.getToken();
if( ! suggestions.contains(suggestion) ) {
suggestions.add(suggestion);
}
}
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
// System.err.println("### " + suggestions);
if( suggestions.size() > 0 ) {
potentialRuleMatch.setSuggestedReplacements(suggestions);
}
ruleMatches.add(potentialRuleMatch);
}
adjTokenReadings.clear();
}
return toRuleMatchArray(ruleMatches);
}
private static String formatInflections(List<Inflection> inflections, boolean adj) {
Collections.sort(inflections);
Map<String, List<String>> map = new LinkedHashMap<>();
for (Inflection inflection : inflections) {
if( ! map.containsKey(inflection.gender) ) {
map.put(inflection.gender, new ArrayList<>());
}
String caseStr = PosTagHelper.VIDMINKY_MAP.get(inflection._case);
if( adj && inflection.animTag != null ) {
caseStr += " (" + (inflection.animTag.equals("ranim") ? "іст." : "неіст.") + ")";
}
map.get(inflection.gender).add(caseStr);
}
List<String> list = new ArrayList<>();
for(Entry<String, List<String>> entry : map.entrySet()) {
String genderStr = PosTagHelper.GENDER_MAP.get(entry.getKey());
List<String> caseValues = entry.getValue();
list.add(genderStr + ": " + StringUtils.join(caseValues, ", "));
}
return StringUtils.join(list, ", ");
}
@Override
public void reset() {
}
}