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