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