]> gitweb.fperrin.net Git - DictionaryPC.git/blob - src/com/hughes/android/dictionary/parser/wiktionary/EnForeignParser.java
Bug-fixes to WikiTokenizer (handle weird line-feed), update to newest
[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.replaceAll("=", "").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           appendAndIndexWikiCallback.onFunction(wikiTokenizer, name, args, namedArgs);
140           
141         } else if (wikiTokenizer.isListItem()) {
142           final String prefix = wikiTokenizer.listItemPrefix();
143           if (lastListSection != null && 
144               prefix.startsWith(lastListSection.firstPrefix) && 
145               prefix.length() > lastListSection.firstPrefix.length()) {
146             lastListSection.nextPrefixes.add(prefix);
147             lastListSection.nextLines.add(wikiTokenizer.listItemWikiText());
148           } else {
149             lastListSection = new ListSection(prefix, wikiTokenizer.listItemWikiText());
150             listSections.add(lastListSection);
151           }
152         } else if (lastListSection != null) {
153           // Don't append anything after the lists, because there's crap.
154         } else if (wikiTokenizer.isWikiLink()) {
155           // Unindexed!
156           foreignBuilder.append(wikiTokenizer.wikiLinkText());
157           
158         } else if (wikiTokenizer.isPlainText()) {
159           // Unindexed!
160           foreignBuilder.append(wikiTokenizer.token());
161           
162         } else if (wikiTokenizer.isMarkup() || wikiTokenizer.isNewline() || wikiTokenizer.isComment()) {
163           // Do nothing.
164         } else {
165           LOG.warning("Unexpected token: " + wikiTokenizer.token());
166           assert !wikiTokenizer.errors().isEmpty();
167         }
168       }
169       
170       } finally {
171         // Here's where we exit.
172         // Should we make an entry even if there are no foreign list items?
173         String foreign = foreignBuilder.toString().trim();
174         if (!titleAppended && !foreign.toLowerCase().startsWith(title.toLowerCase())) {
175           foreign = String.format("%s %s", title, foreign);
176         }
177         if (!langPattern.matcher(lang).matches()) {
178           foreign = String.format("(%s) %s", lang, foreign);
179         }
180         for (final EnForeignParser.ListSection listSection : listSections) {
181           doForeignListSection(foreign, title, wordForms, listSection);
182         }
183       }
184     }
185     
186     private void doForeignListSection(final String foreignText, String title, final Collection<String> forms, final EnForeignParser.ListSection listSection) {
187       state = State.ENGLISH_DEF_OF_FOREIGN;
188       final String prefix = listSection.firstPrefix;
189       if (prefix.length() > 1) {
190         // Could just get looser and say that any prefix longer than first is a sublist.
191         LOG.warning("Prefix too long: " + listSection);
192         incrementCount("WARNING: Prefix too long");
193         return;
194       }
195       
196       final PairEntry pairEntry = new PairEntry(entrySource);
197       final IndexedEntry indexedEntry = new IndexedEntry(pairEntry);
198
199       entryIsFormOfSomething = false;
200       final StringBuilder englishBuilder = new StringBuilder();
201       final String mainLine = listSection.firstLine;
202       appendAndIndexWikiCallback.reset(englishBuilder, indexedEntry);
203       appendAndIndexWikiCallback.dispatch(mainLine, enIndexBuilder, EntryTypeName.WIKTIONARY_ENGLISH_DEF);
204
205       final String english = trim(englishBuilder.toString());
206       if (english.length() > 0) {
207         final Pair pair = new Pair(english, trim(foreignText), this.swap);
208         pairEntry.pairs.add(pair);
209         foreignIndexBuilder.addEntryWithString(indexedEntry, title, entryIsFormOfSomething ? EntryTypeName.WIKTIONARY_IS_FORM_OF_SOMETHING_ELSE : EntryTypeName.WIKTIONARY_TITLE_MULTI);
210         for (final String form : forms) {
211           foreignIndexBuilder.addEntryWithString(indexedEntry, form, EntryTypeName.WIKTIONARY_INFLECTED_FORM_MULTI);
212         }
213       }
214       
215       // Do examples.
216       String lastForeign = null;
217       for (int i = 0; i < listSection.nextPrefixes.size(); ++i) {
218         final String nextPrefix = listSection.nextPrefixes.get(i);
219         final String nextLine = listSection.nextLines.get(i);
220
221         // TODO: This splitting is not sensitive to wiki code.
222         int dash = nextLine.indexOf("&mdash;");
223         int mdashLen = 7;
224         if (dash == -1) {
225           dash = nextLine.indexOf("—");
226           mdashLen = 1;
227         }
228         if (dash == -1) {
229           dash = nextLine.indexOf(" - ");
230           mdashLen = 3;
231         }
232         
233         if ((nextPrefix.equals("#:") || nextPrefix.equals("##:")) && dash != -1) {
234           final String foreignEx = nextLine.substring(0, dash);
235           final String englishEx = nextLine.substring(dash + mdashLen);
236           final Pair pair = new Pair(formatAndIndexExampleString(englishEx, enIndexBuilder, indexedEntry), formatAndIndexExampleString(foreignEx, foreignIndexBuilder, indexedEntry), swap);
237           if (pair.lang1 != "--" && pair.lang1 != "--") {
238             pairEntry.pairs.add(pair);
239           }
240           lastForeign = null;
241         } else if (nextPrefix.equals("#:") || nextPrefix.equals("##:")){
242           final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
243           lastForeign = nextLine;
244           if (pair.lang1 != "--" && pair.lang1 != "--") {
245             pairEntry.pairs.add(pair);
246           }
247         } else if (nextPrefix.equals("#::") || nextPrefix.equals("#**")) {
248           if (lastForeign != null && pairEntry.pairs.size() > 0) {
249             pairEntry.pairs.remove(pairEntry.pairs.size() - 1);
250             final Pair pair = new Pair(formatAndIndexExampleString(nextLine, enIndexBuilder, indexedEntry), formatAndIndexExampleString(lastForeign, foreignIndexBuilder, indexedEntry), swap);
251             if (pair.lang1 != "--" || pair.lang2 != "--") {
252               pairEntry.pairs.add(pair);
253             }
254             lastForeign = null;
255           } else {
256             LOG.warning("TODO: English example with no foreign: " + title + ", " + nextLine);
257             final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
258             if (pair.lang1 != "--" || pair.lang2 != "--") {
259               pairEntry.pairs.add(pair);
260             }
261           }
262         } else if (nextPrefix.equals("#*")) {
263           // Can't really index these.
264           final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
265           lastForeign = nextLine;
266           if (pair.lang1 != "--" || pair.lang2 != "--") {
267             pairEntry.pairs.add(pair);
268           }
269         } else if (nextPrefix.equals("#::*") || nextPrefix.equals("##") || nextPrefix.equals("#*:") || nextPrefix.equals("#:*") || true) {
270           final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
271           if (pair.lang1 != "--" || pair.lang2 != "--") {
272             pairEntry.pairs.add(pair);
273           }
274 //        } else {
275 //          assert false;
276         }
277       }
278     }
279     
280     private String formatAndIndexExampleString(final String example, final IndexBuilder indexBuilder, final IndexedEntry indexedEntry) {
281       // TODO:
282 //      if (wikiTokenizer.token().equals("'''")) {
283 //        insideTripleQuotes = !insideTripleQuotes;
284 //      }
285       final StringBuilder builder = new StringBuilder();
286       appendAndIndexWikiCallback.reset(builder, indexedEntry);
287       appendAndIndexWikiCallback.entryTypeName = EntryTypeName.WIKTIONARY_EXAMPLE;
288       appendAndIndexWikiCallback.entryTypeNameSticks = true;
289       try {
290         // TODO: this is a hack needed because we don't safely split on the dash.
291         appendAndIndexWikiCallback.dispatch(example, indexBuilder, EntryTypeName.WIKTIONARY_EXAMPLE);
292       } catch (AssertionError e) {
293         return "--";
294       }
295       final String result = trim(builder.toString());
296       return result.length() > 0 ? result : "--";
297     }
298
299
300     private void itConjAre(List<String> args, Map<String, String> namedArgs) {
301       final String base = args.get(0);
302       final String aux = args.get(1);
303       
304       putIfMissing(namedArgs, "inf", base + "are");
305       putIfMissing(namedArgs, "aux", aux);
306       putIfMissing(namedArgs, "ger", base + "ando");
307       putIfMissing(namedArgs, "presp", base + "ante");
308       putIfMissing(namedArgs, "pastp", base + "ato");
309       // Present
310       putIfMissing(namedArgs, "pres1s", base + "o");
311       putIfMissing(namedArgs, "pres2s", base + "i");
312       putIfMissing(namedArgs, "pres3s", base + "a");
313       putIfMissing(namedArgs, "pres1p", base + "iamo");
314       putIfMissing(namedArgs, "pres2p", base + "ate");
315       putIfMissing(namedArgs, "pres3p", base + "ano");
316       // Imperfect
317       putIfMissing(namedArgs, "imperf1s", base + "avo");
318       putIfMissing(namedArgs, "imperf2s", base + "avi");
319       putIfMissing(namedArgs, "imperf3s", base + "ava");
320       putIfMissing(namedArgs, "imperf1p", base + "avamo");
321       putIfMissing(namedArgs, "imperf2p", base + "avate");
322       putIfMissing(namedArgs, "imperf3p", base + "avano");
323       // Passato remoto
324       putIfMissing(namedArgs, "prem1s", base + "ai");
325       putIfMissing(namedArgs, "prem2s", base + "asti");
326       putIfMissing(namedArgs, "prem3s", base + "ò");
327       putIfMissing(namedArgs, "prem1p", base + "ammo");
328       putIfMissing(namedArgs, "prem2p", base + "aste");
329       putIfMissing(namedArgs, "prem3p", base + "arono");
330       // Future
331       putIfMissing(namedArgs, "fut1s", base + "erò");
332       putIfMissing(namedArgs, "fut2s", base + "erai");
333       putIfMissing(namedArgs, "fut3s", base + "erà");
334       putIfMissing(namedArgs, "fut1p", base + "eremo");
335       putIfMissing(namedArgs, "fut2p", base + "erete");
336       putIfMissing(namedArgs, "fut3p", base + "eranno");
337       // Conditional
338       putIfMissing(namedArgs, "cond1s", base + "erei");
339       putIfMissing(namedArgs, "cond2s", base + "eresti");
340       putIfMissing(namedArgs, "cond3s", base + "erebbe");
341       putIfMissing(namedArgs, "cond1p", base + "eremmo");
342       putIfMissing(namedArgs, "cond2p", base + "ereste");
343       putIfMissing(namedArgs, "cond3p", base + "erebbero");
344       // Subjunctive / congiuntivo
345       putIfMissing(namedArgs, "sub123s", base + "i");
346       putIfMissing(namedArgs, "sub1p", base + "iamo");
347       putIfMissing(namedArgs, "sub2p", base + "iate");
348       putIfMissing(namedArgs, "sub3p", base + "ino");
349       // Imperfect subjunctive
350       putIfMissing(namedArgs, "impsub12s", base + "assi");
351       putIfMissing(namedArgs, "impsub3s", base + "asse");
352       putIfMissing(namedArgs, "impsub1p", base + "assimo");
353       putIfMissing(namedArgs, "impsub2p", base + "aste");
354       putIfMissing(namedArgs, "impsub3p", base + "assero");
355       // Imperative
356       putIfMissing(namedArgs, "imp2s", base + "a");
357       putIfMissing(namedArgs, "imp3s", base + "i");
358       putIfMissing(namedArgs, "imp1p", base + "iamo");
359       putIfMissing(namedArgs, "imp2p", base + "ate");
360       putIfMissing(namedArgs, "imp3p", base + "ino");
361
362
363       itConj(args, namedArgs);
364     }
365
366
367     private void itConj(List<String> args, Map<String, String> namedArgs) {
368       // TODO Auto-generated method stub
369       
370     }
371
372
373     private static void putIfMissing(final Map<String, String> namedArgs, final String key,
374         final String value) {
375       final String oldValue = namedArgs.get(key);
376       if (oldValue == null || oldValue.length() == 0) {
377         namedArgs.put(key, value);
378       }
379     }
380     
381     // TODO: check how ='' and =| are manifested....
382     // TODO: get this right in -are
383     private static void putOrNullify(final Map<String, String> namedArgs, final String key,
384         final String value) {
385       final String oldValue = namedArgs.get(key);
386       if (oldValue == null/* || oldValue.length() == 0*/) {
387         namedArgs.put(key, value);
388       } else {
389         if (oldValue.equals("''")) {
390           namedArgs.put(key, "");
391         }
392       }
393     }
394
395   }  // ForeignParser