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