]> gitweb.fperrin.net Git - DictionaryPC.git/blob - src/com/hughes/android/dictionary/parser/wiktionary/EnForeignParser.java
Minor automated code simplifications.
[DictionaryPC.git] / src / com / hughes / android / dictionary / parser / wiktionary / EnForeignParser.java
1 // Copyright 2012 Google Inc. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package com.hughes.android.dictionary.parser.wiktionary;
16
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.regex.Pattern;
22
23 import com.hughes.android.dictionary.engine.EntryTypeName;
24 import com.hughes.android.dictionary.engine.IndexBuilder;
25 import com.hughes.android.dictionary.engine.IndexedEntry;
26 import com.hughes.android.dictionary.engine.PairEntry;
27 import com.hughes.android.dictionary.parser.WikiTokenizer;
28
29 public final class EnForeignParser extends EnParser {
30
31     public EnForeignParser(final IndexBuilder enIndexBuilder,
32                            final IndexBuilder otherIndexBuilder, final Pattern langPattern,
33                            final Pattern langCodePattern, final boolean swap) {
34         super(enIndexBuilder, otherIndexBuilder, langPattern, langCodePattern, swap);
35     }
36
37     @Override
38     void parseSection(String heading, String text) {
39         if (isIgnorableTitle(title)) {
40             return;
41         }
42         final String lang = heading.replace("=", "").trim();
43         if (!langPattern.matcher(lang).find()) {
44             return;
45         }
46
47         final WikiTokenizer wikiTokenizer = new WikiTokenizer(text);
48         while (wikiTokenizer.nextToken() != null) {
49             if (wikiTokenizer.isHeading()) {
50                 final String headingName = wikiTokenizer.headingWikiText();
51                 if (headingName.equals("Translations")) {
52                     LOG.warning("Translations not in English section: " + title);
53                     incrementCount("WARNING: Translations not in English section");
54                 } else if (headingName.equals("Pronunciation")) {
55                     //doPronunciation(wikiLineReader);
56                 } else if (headingName.startsWith(" {{S|")) {
57                     // HACK to support parsing frwiktionary
58                     String[] parts = headingName.split("\\|");
59                     if (parts.length > 2 && langCodePattern.matcher(parts[2]).find() &&
60                             (parts.length < 4 || !parts[3].startsWith("flexion"))) {
61                         doForeignPartOfSpeech(lang, headingName, wikiTokenizer.headingDepth(), wikiTokenizer);
62                     }
63                 } else if (partOfSpeechHeader.matcher(headingName).matches()) {
64                     doForeignPartOfSpeech(lang, headingName, wikiTokenizer.headingDepth(), wikiTokenizer);
65                 }
66             } else {
67                 // It's not a heading.
68                 // TODO: optimization: skip to next heading.
69             }
70         }
71     }
72
73     static final class ListSection {
74         final String firstPrefix;
75         final String firstLine;
76         final List<String> nextPrefixes = new ArrayList<>();
77         final List<String> nextLines = new ArrayList<>();
78
79         public ListSection(String firstPrefix, String firstLine) {
80             this.firstPrefix = firstPrefix;
81             this.firstLine = firstLine;
82         }
83
84         @Override
85         public String toString() {
86             return firstPrefix + firstLine + "{ " + nextPrefixes + "}";
87         }
88     }
89
90     int foreignCount = 0;
91     private void doForeignPartOfSpeech(final String lang, String posHeading, final int posDepth, WikiTokenizer wikiTokenizer) {
92         if (++foreignCount % 1000 == 0) {
93             LOG.info("***" + lang + ", " + title + ", pos=" + posHeading + ", foreignCount=" + foreignCount);
94         }
95         if (title.equals("6")) {
96             System.out.println();
97         }
98
99         final StringBuilder foreignBuilder = new StringBuilder();
100         final List<EnForeignParser.ListSection> listSections = new ArrayList<>();
101
102         appendAndIndexWikiCallback.reset(foreignBuilder, null);
103         this.state = State.ENGLISH_DEF_OF_FOREIGN;  // TODO: this is wrong, need new category....
104         titleAppended = false;
105         wordForms.clear();
106
107         try {
108
109             EnForeignParser.ListSection lastListSection = null;
110
111             int currentHeadingDepth = posDepth;
112             while (wikiTokenizer.nextToken() != null) {
113                 if (wikiTokenizer.isHeading()) {
114                     currentHeadingDepth = wikiTokenizer.headingDepth();
115
116                     if (currentHeadingDepth <= posDepth) {
117                         wikiTokenizer.returnToLineStart();
118                         return;
119                     }
120                 }  // heading
121
122                 if (currentHeadingDepth > posDepth) {
123                     // TODO: deal with other neat info sections inside POS
124                     continue;
125                 }
126
127                 if (wikiTokenizer.isFunction()) {
128                     final String name = wikiTokenizer.functionName();
129                     final List<String> args = wikiTokenizer.functionPositionArgs();
130                     final Map<String,String> namedArgs = wikiTokenizer.functionNamedArgs();
131                     // First line is generally a repeat of the title with some extra information.
132                     // We need to build up the left side (foreign text, tokens) separately from the
133                     // right side (English).  The left-side may get paired with multiple right sides.
134                     // The left side should get filed under every form of the word in question (singular, plural).
135
136                     // For verbs, the conjugation comes later on in a deeper section.
137                     // Ideally, we'd want to file every English entry with the verb
138                     // under every verb form coming from the conjugation.
139                     // Ie. under "fa": see: "make :: fare" and "do :: fare"
140                     // But then where should we put the conjugation table?
141                     // I think just under fare.  But then we need a way to link to the entry (actually the row, since entries doesn't show up!)
142                     // for the conjugation table from "fa".
143                     // Would like to be able to link to a lang#token.
144
145
146                     String head = namedArgs.remove("head");
147                     final String tr = namedArgs.remove("tr");
148                     if (head == null && tr != null && !titleAppended) {
149                         head = title;
150                     }
151                     if (head != null) {
152                         final String form = appendAndIndexWikiCallback.dispatch(head, EntryTypeName.WIKTIONARY_TITLE_MULTI);
153                         wordForms.add(form);
154                         appendAndIndexWikiCallback.builder.append(" ");
155                         titleAppended = true;
156                     }
157                     if (tr != null) {
158                         appendAndIndexWikiCallback.builder.append(" (");
159                         final String form = appendAndIndexWikiCallback.dispatch(tr, EntryTypeName.WIKTIONARY_TRANSLITERATION);
160                         wordForms.add(form);
161                         appendAndIndexWikiCallback.builder.append(") ");
162                     }
163
164                     appendAndIndexWikiCallback.onFunction(wikiTokenizer, name, args, namedArgs);
165
166                 } else if (wikiTokenizer.isListItem()) {
167                     final String prefix = wikiTokenizer.listItemPrefix();
168                     if (lastListSection != null &&
169                             prefix.startsWith(lastListSection.firstPrefix) &&
170                             prefix.length() > lastListSection.firstPrefix.length()) {
171                         lastListSection.nextPrefixes.add(prefix);
172                         lastListSection.nextLines.add(wikiTokenizer.listItemWikiText());
173                     } else {
174                         lastListSection = new ListSection(prefix, wikiTokenizer.listItemWikiText());
175                         listSections.add(lastListSection);
176                     }
177                 } else if (lastListSection != null) {
178                     // Don't append anything after the lists, because there's crap.
179                 } else if (wikiTokenizer.isWikiLink()) {
180                     // Unindexed!
181                     foreignBuilder.append(wikiTokenizer.wikiLinkText());
182
183                 } else if (wikiTokenizer.isPlainText()) {
184                     // Unindexed!
185                     foreignBuilder.append(wikiTokenizer.token());
186                 } else if (wikiTokenizer.isHtml()) {
187                     if (!wikiTokenizer.token().startsWith("<ref>")) {
188                         foreignBuilder.append(wikiTokenizer.token());
189                     }
190                 } else if (wikiTokenizer.isMarkup() ||
191                            wikiTokenizer.isNewline() ||
192                            wikiTokenizer.isComment()) {
193                     // Do nothing.
194                 } else {
195                     LOG.warning("Unexpected token: " + wikiTokenizer.token());
196                     assert !wikiTokenizer.errors().isEmpty();
197                 }
198             }
199
200         } finally {
201             // Here's where we exit.
202             // Should we make an entry even if there are no foreign list items?
203             String foreign = foreignBuilder.toString().trim();
204             if (!titleAppended && !foreign.toLowerCase().startsWith(title.toLowerCase())) {
205                 foreign = String.format("%s %s", title, foreign);
206             }
207             if (!langPattern.matcher(lang).matches()) {
208                 foreign = String.format("(%s) %s", lang, foreign);
209             }
210             for (final EnForeignParser.ListSection listSection : listSections) {
211                 doForeignListSection(foreign, title, wordForms, listSection);
212             }
213         }
214     }
215
216     private void doForeignListSection(final String foreignText, String title, final Collection<String> forms, final EnForeignParser.ListSection listSection) {
217         state = State.ENGLISH_DEF_OF_FOREIGN;
218         final String prefix = listSection.firstPrefix;
219         if (prefix.length() > 1) {
220             // Could just get looser and say that any prefix longer than first is a sublist.
221             LOG.warning("Prefix '" + prefix + "' too long: " + listSection);
222             incrementCount("WARNING: Prefix too long");
223             return;
224         }
225
226         final PairEntry pairEntry = new PairEntry(entrySource);
227         final IndexedEntry indexedEntry = new IndexedEntry(pairEntry);
228         indexedEntry.isValid = true;
229
230         entryIsFormOfSomething = false;
231         final StringBuilder englishBuilder = new StringBuilder();
232         final String mainLine = listSection.firstLine;
233         appendAndIndexWikiCallback.reset(englishBuilder, indexedEntry);
234         appendAndIndexWikiCallback.dispatch(mainLine, enIndexBuilder, EntryTypeName.WIKTIONARY_ENGLISH_DEF);
235
236         final String english = trim(englishBuilder.toString());
237         if (english.length() > 0) {
238             final PairEntry.Pair pair = new PairEntry.Pair(english, trim(foreignText), this.swap);
239             pairEntry.pairs.add(pair);
240             foreignIndexBuilder.addEntryWithString(indexedEntry, title, entryIsFormOfSomething ? EntryTypeName.WIKTIONARY_IS_FORM_OF_SOMETHING_ELSE : EntryTypeName.WIKTIONARY_TITLE_MULTI);
241             for (final String form : forms) {
242                 foreignIndexBuilder.addEntryWithString(indexedEntry, form, EntryTypeName.WIKTIONARY_INFLECTED_FORM_MULTI);
243             }
244         }
245
246         // Do examples.
247         String lastForeign = null;
248         for (int i = 0; i < listSection.nextPrefixes.size(); ++i) {
249             final String nextPrefix = listSection.nextPrefixes.get(i);
250             String nextLine = listSection.nextLines.get(i);
251
252             // TODO: This splitting is not sensitive to wiki code.
253             int dash = nextLine.indexOf("&mdash;");
254             int mdashLen = 7;
255             if (dash == -1) {
256                 dash = nextLine.indexOf("—");
257                 mdashLen = 1;
258             }
259             if (dash == -1) {
260                 dash = nextLine.indexOf(" - ");
261                 mdashLen = 3;
262             }
263
264             if ((nextPrefix.equals("#:") || nextPrefix.equals("##:")) && dash != -1) {
265                 final String foreignEx = nextLine.substring(0, dash);
266                 final String englishEx = nextLine.substring(dash + mdashLen);
267                 final PairEntry.Pair pair = new PairEntry.Pair(formatAndIndexExampleString(englishEx, enIndexBuilder, indexedEntry), formatAndIndexExampleString(foreignEx, foreignIndexBuilder, indexedEntry), swap);
268                 if (pair.lang1 != "--" && pair.lang1 != "--") {
269                     pairEntry.pairs.add(pair);
270                 }
271                 lastForeign = null;
272                 // TODO: make #* and #*: work
273             } else if (nextPrefix.equals("#:") || nextPrefix.equals("##:")/* || nextPrefix.equals("#*")*/) {
274                 final PairEntry.Pair pair = new PairEntry.Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
275                 lastForeign = nextLine;
276                 if (pair.lang1 != "--" && pair.lang1 != "--") {
277                     pairEntry.pairs.add(pair);
278                 }
279             } else if (nextPrefix.equals("#::") || nextPrefix.equals("#**")/* || nextPrefix.equals("#*:")*/) {
280                 if (lastForeign != null && pairEntry.pairs.size() > 0) {
281                     if (i + 1 < listSection.nextPrefixes.size()) {
282                         // Chinese has sometimes multiple foreign lines
283                         final String nextNextPrefix = listSection.nextPrefixes.get(i + 1);
284                         if (nextNextPrefix.equals("#::") || nextNextPrefix.equals("#**")) {
285                             ++i;
286                             nextLine += "\n" + listSection.nextLines.get(i);
287                         }
288                     }
289                     pairEntry.pairs.remove(pairEntry.pairs.size() - 1);
290                     final PairEntry.Pair pair = new PairEntry.Pair(formatAndIndexExampleString(nextLine, enIndexBuilder, indexedEntry), formatAndIndexExampleString(lastForeign, foreignIndexBuilder, indexedEntry), swap);
291                     if (pair.lang1 != "--" || pair.lang2 != "--") {
292                         pairEntry.pairs.add(pair);
293                     }
294                     lastForeign = null;
295                 } else {
296                     LOG.warning("TODO: English example with no foreign: " + title + ", " + nextLine);
297                     final PairEntry.Pair pair = new PairEntry.Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
298                     if (pair.lang1 != "--" || pair.lang2 != "--") {
299                         pairEntry.pairs.add(pair);
300                     }
301                 }
302             } else if (nextPrefix.equals("#*")) {
303                 // Can't really index these.
304                 final PairEntry.Pair pair = new PairEntry.Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
305                 lastForeign = nextLine;
306                 if (pair.lang1 != "--" || pair.lang2 != "--") {
307                     pairEntry.pairs.add(pair);
308                 }
309             } else if (nextPrefix.equals("#::*") || nextPrefix.equals("##") || nextPrefix.equals("#*:") || nextPrefix.equals("#:*") || true) {
310                 final PairEntry.Pair pair = new PairEntry.Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
311                 if (pair.lang1 != "--" || pair.lang2 != "--") {
312                     pairEntry.pairs.add(pair);
313                 }
314 //        } else {
315 //          assert false;
316             }
317         }
318     }
319
320     private String formatAndIndexExampleString(final String example, final IndexBuilder indexBuilder, final IndexedEntry indexedEntry) {
321         // TODO:
322 //      if (wikiTokenizer.token().equals("'''")) {
323 //        insideTripleQuotes = !insideTripleQuotes;
324 //      }
325         final StringBuilder builder = new StringBuilder();
326         appendAndIndexWikiCallback.reset(builder, indexedEntry);
327         appendAndIndexWikiCallback.entryTypeName = EntryTypeName.WIKTIONARY_EXAMPLE;
328         appendAndIndexWikiCallback.entryTypeNameSticks = true;
329         try {
330             // TODO: this is a hack needed because we don't safely split on the dash.
331             appendAndIndexWikiCallback.dispatch(example, indexBuilder, EntryTypeName.WIKTIONARY_EXAMPLE);
332         } catch (AssertionError e) {
333             return "--";
334         }
335         final String result = trim(builder.toString());
336         return result.length() > 0 ? result : "--";
337     }
338
339
340 }  // ForeignParser