]> gitweb.fperrin.net Git - DictionaryPC.git/blob - src/com/hughes/android/dictionary/parser/EnWiktionaryXmlParser.java
Handling {{infl}}
[DictionaryPC.git] / src / com / hughes / android / dictionary / parser / EnWiktionaryXmlParser.java
1 // Copyright 2011 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;
16
17 import java.io.BufferedInputStream;
18 import java.io.DataInputStream;
19 import java.io.EOFException;
20 import java.io.File;
21 import java.io.FileInputStream;
22 import java.io.IOException;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.LinkedHashSet;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Set;
30 import java.util.logging.Logger;
31 import java.util.regex.Pattern;
32
33 import com.hughes.android.dictionary.engine.EntryTypeName;
34 import com.hughes.android.dictionary.engine.IndexBuilder;
35 import com.hughes.android.dictionary.engine.IndexedEntry;
36 import com.hughes.android.dictionary.engine.PairEntry;
37 import com.hughes.android.dictionary.engine.PairEntry.Pair;
38
39 public class EnWiktionaryXmlParser {
40   
41   private static final String TRANSLITERATION_FORMAT = " (tr. %s)";
42
43   static final Logger LOG = Logger.getLogger(EnWiktionaryXmlParser.class.getName());
44   
45   // TODO: process {{ttbc}} lines
46   
47   static final Pattern partOfSpeechHeader = Pattern.compile(
48       "Noun|Verb|Adjective|Adverb|Pronoun|Conjunction|Interjection|" +
49       "Preposition|Proper noun|Article|Prepositional phrase|Acronym|" +
50       "Abbreviation|Initialism|Contraction|Prefix|Suffix|Symbol|Letter|" +
51       "Ligature|Idiom|Phrase|\\{\\{acronym\\}\\}|\\{\\{initialism\\}\\}|" +
52       // These are @deprecated:
53       "Noun form|Verb form|Adjective form|Nominal phrase|Noun phrase|" +
54       "Verb phrase|Transitive verb|Intransitive verb|Reflexive verb|" +
55       // These are extras I found:
56       "Determiner|Numeral|Number|Cardinal number|Ordinal number|Proverb|" +
57       "Particle|Interjection|Pronominal adverb" +
58       "Han character|Hanzi|Hanja|Kanji|Katakana character|Syllable");
59   
60   final IndexBuilder enIndexBuilder;
61   final IndexBuilder otherIndexBuilder;
62   final Pattern langPattern;
63   final Pattern langCodePattern;
64   final boolean swap;
65
66   public EnWiktionaryXmlParser(final IndexBuilder enIndexBuilder, final IndexBuilder otherIndexBuilder, final Pattern langPattern, final Pattern langCodePattern, final boolean swap) {
67     this.enIndexBuilder = enIndexBuilder;
68     this.otherIndexBuilder = otherIndexBuilder;
69     this.langPattern = langPattern;
70     this.langCodePattern = langCodePattern;
71     this.swap = swap;
72   }
73
74   
75   public void parse(final File file, final int pageLimit) throws IOException {
76     int pageCount = 0;
77     final DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
78     while (true) {
79       if (pageLimit >= 0 && pageCount >= pageLimit) {
80         return;
81       }
82       
83       final String title;
84       try {
85         title = dis.readUTF();
86       } catch (EOFException e) {
87         dis.close();
88         return;
89       }
90       final String heading = dis.readUTF();
91       final int bytesLength = dis.readInt();
92       final byte[] bytes = new byte[bytesLength];
93       dis.readFully(bytes);
94       final String text = new String(bytes, "UTF8");
95       
96       parseSection(title, heading, text);
97
98       ++pageCount;
99       if (pageCount % 1000 == 0) {
100         LOG.info("pageCount=" + pageCount);
101       }
102     }
103   }
104   
105   private void parseSection(final String title, String heading, final String text) {
106     if (title.startsWith("Wiktionary:") ||
107         title.startsWith("Template:") ||
108         title.startsWith("Appendix:") ||
109         title.startsWith("Category:") ||
110         title.startsWith("Index:") ||
111         title.startsWith("MediaWiki:") ||
112         title.startsWith("TransWiki:") ||
113         title.startsWith("Citations:") ||
114         title.startsWith("Concordance:") ||
115         title.startsWith("Help:")) {
116       return;
117     }
118     
119     heading = heading.replaceAll("=", "").trim(); 
120     if (heading.equals("English")) {
121       doEnglishWord(title, text);
122     } else if (langPattern.matcher(heading).find()){
123       doForeignWord(heading, title, text);
124     }
125         
126   }  // endPage()
127   
128   // -------------------------------------------------------------------------
129   
130   private void doEnglishWord(String title, String text) {
131     
132     String pos = null;
133     int posDepth = -1;
134
135     final WikiTokenizer wikiTokenizer = new WikiTokenizer(text);
136     while (wikiTokenizer.nextToken() != null) {
137       
138       if (wikiTokenizer.isHeading()) {
139         final String headerName = wikiTokenizer.headingWikiText();
140         
141         if (wikiTokenizer.headingDepth() <= posDepth) {
142           pos = null;
143           posDepth = -1;
144         }
145         
146         if (partOfSpeechHeader.matcher(headerName).matches()) {
147           posDepth = wikiTokenizer.headingDepth();
148           pos = wikiTokenizer.headingWikiText();
149           // TODO: if we're inside the POS section, we should handle the first title line...
150           
151         } else if (headerName.equals("Translations")) {
152           if (pos == null) {
153             LOG.warning("Translations without POS: " + title);
154           }
155           doTranslations(title, wikiTokenizer, pos);
156         } else if (headerName.equals("Pronunciation")) {
157           //doPronunciation(wikiLineReader);
158         }
159       }
160     }
161   }
162
163
164   private static Set<String> encodings = new LinkedHashSet<String>(Arrays.asList("zh-ts",
165       "sd-Arab", "ku-Arab", "Arab", "unicode", "Laoo", "ur-Arab", "Thai", 
166       "fa-Arab", "Khmr", "zh-tsp", "Cyrl", "IPAchar", "ug-Arab", "ko-inline", 
167       "Jpan", "Kore", "Hebr", "rfscript", "Beng", "Mong", "Knda", "Cyrs",
168       "yue-tsj", "Mlym", "Tfng", "Grek", "yue-yue-j"));
169   
170   private void doTranslations(final String title, final WikiTokenizer wikiTokenizer, final String pos) {
171     if (title.equals("absolutely")) {
172       //System.out.println();
173     }
174     
175     String topLevelLang = null;
176     String sense = null;
177     boolean done = false;
178     while (wikiTokenizer.nextToken() != null) {
179       if (wikiTokenizer.isHeading()) {
180         wikiTokenizer.returnToLineStart();
181         return;
182       }
183       if (done) {
184         continue;
185       }
186       
187       // Check whether we care about this line:
188       
189       if (wikiTokenizer.isFunction()) {
190         final String functionName = wikiTokenizer.functionName();
191         final List<String> positionArgs = wikiTokenizer.functionPositionArgs();
192         
193         if (functionName.equals("trans-top")) {
194           sense = null;
195           if (wikiTokenizer.functionPositionArgs().size() >= 1) {
196             sense = positionArgs.get(0);
197             // TODO: could emphasize words in [[brackets]] inside sense.
198             sense = WikiTokenizer.toPlainText(sense);
199             //LOG.info("Sense: " + sense);
200           }
201         } else if (functionName.equals("trans-bottom")) {
202           sense = null;
203         } else if (functionName.equals("trans-mid")) {
204         } else if (functionName.equals("trans-see")) {
205           // TODO: would also be nice...
206         } else if (functionName.startsWith("picdic")) {
207         } else if (functionName.startsWith("checktrans")) {
208           done = true;
209         } else if (functionName.startsWith("ttbc")) {
210           wikiTokenizer.nextLine();
211           // TODO: would be great to handle ttbc
212           // TODO: Check this: done = true;
213         } else {
214           LOG.warning("Unexpected translation wikifunction: " + wikiTokenizer.token() + ", title=" + title);
215         }
216       } else if (wikiTokenizer.isListItem()) {
217         final String line = wikiTokenizer.listItemWikiText();
218         // This line could produce an output...
219         
220         if (line.contains("ich hoan dich gear")) {
221           //System.out.println();
222         }
223         
224         // First strip the language and check whether it matches.
225         // And hold onto it for sub-lines.
226         final int colonIndex = line.indexOf(":");
227         if (colonIndex == -1) {
228           continue;
229         }
230         
231         final String lang = trim(WikiTokenizer.toPlainText(line.substring(0, colonIndex)));
232         final boolean appendLang;
233         if (wikiTokenizer.listItemPrefix().length() == 1) {
234           topLevelLang = lang;
235           final boolean thisFind = langPattern.matcher(lang).find();
236           if (!thisFind) {
237             continue;
238           }
239           appendLang = !langPattern.matcher(lang).matches();
240         } else if (topLevelLang == null) {
241           continue;
242         } else {
243           // Two-level -- the only way we won't append is if this second level matches exactly.
244           if (!langPattern.matcher(lang).matches() && !langPattern.matcher(topLevelLang).find()) {
245             continue;
246           }
247           appendLang = !langPattern.matcher(lang).matches();
248         }
249         
250         String rest = line.substring(colonIndex + 1).trim();
251         if (rest.length() > 0) {
252           doTranslationLine(line, appendLang ? lang : null, title, pos, sense, rest);
253         }
254         
255       } else if (wikiTokenizer.remainderStartsWith("''See''")) {
256         wikiTokenizer.nextLine();
257         LOG.fine("Skipping line: " + wikiTokenizer.token());
258       } else if (wikiTokenizer.isWikiLink()) {
259         final String wikiLink = wikiTokenizer.wikiLinkText();
260         if (wikiLink.contains(":") && wikiLink.contains(title)) {
261         } else if (wikiLink.contains("Category:")) {
262         } else  {
263           LOG.warning("Unexpected wikiLink: " + wikiTokenizer.token() + ", title=" + title);
264         }
265       } else if (wikiTokenizer.isNewline() || wikiTokenizer.isMarkup() || wikiTokenizer.isComment()) {
266       } else {
267         final String token = wikiTokenizer.token();
268         if (token.equals("----")) { 
269         } else {
270           LOG.warning("Unexpected translation token: " + wikiTokenizer.token() + ", title=" + title);
271         }
272       }
273       
274     }
275   }
276   
277   private static <T> T get(final List<T> list, final int index) {
278     return index < list.size() ? list.get(index) : null;
279   }
280   
281   private void doTranslationLine(final String line, final String lang, final String title, final String pos, final String sense, final String rest) {
282     // Good chance we'll actually file this one...
283     final PairEntry pairEntry = new PairEntry();
284     final IndexedEntry indexedEntry = new IndexedEntry(pairEntry);
285     
286     final StringBuilder otherText = new StringBuilder();
287     final WikiTokenizer wikiTokenizer = new WikiTokenizer(rest, false);
288     while (wikiTokenizer.nextToken() != null) {
289       
290       if (wikiTokenizer.isPlainText()) {
291         final String plainText = wikiTokenizer.token(); 
292         otherText.append("").append(plainText);
293         otherIndexBuilder.addEntryWithString(indexedEntry, plainText, EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
294         
295       } else if (wikiTokenizer.isWikiLink()) {
296         final String plainText = wikiTokenizer.wikiLinkText(); 
297         otherText.append("").append(plainText);
298         otherIndexBuilder.addEntryWithString(indexedEntry, plainText, EntryTypeName.WIKTIONARY_TRANSLATION_WIKI_TEXT);
299         
300       } else if (wikiTokenizer.isFunction()) {
301         final String functionName = wikiTokenizer.functionName();
302         final List<String> args = wikiTokenizer.functionPositionArgs();
303         final Map<String,String> namedArgs = wikiTokenizer.functionNamedArgs();
304         
305         if (functionName.equals("t") || functionName.equals("t+") || functionName.equals("t-") || functionName.equals("tø") || functionName.equals("apdx-t")) {
306           if (args.size() < 2) {
307             LOG.warning("{{t}} with too few args: " + line + ", title=" + title);
308             continue;
309           }
310           final String langCode = get(args, 0);
311           //if (this.langCodePattern.matcher(langCode).matches()) {
312             final String word = get(args, 1);
313             final String gender = get(args, 2);
314             final String transliteration = namedArgs.get("tr");
315             if (otherText.length() > 0) {
316               otherText.append("");
317             }
318             otherText.append(word);
319             otherIndexBuilder.addEntryWithString(indexedEntry, word, EntryTypeName.WIKTIONARY_TITLE_SINGLE, EntryTypeName.WIKTIONARY_TITLE_MULTI);
320             if (gender != null) {
321               otherText.append(String.format(" {%s}", gender));
322             }
323             if (transliteration != null) {
324               otherText.append(String.format(TRANSLITERATION_FORMAT, transliteration));
325               otherIndexBuilder.addEntryWithString(indexedEntry, transliteration, EntryTypeName.WIKTIONARY_TRANSLITERATION);
326             }
327           //}
328         } else if (functionName.equals("qualifier")) {
329           if (args.size() == 0) {
330            otherText.append(wikiTokenizer.token()); 
331           } else { 
332             String qualifier = args.get(0);
333             if (!namedArgs.isEmpty() || args.size() > 1) {
334               LOG.warning("weird qualifier: " + line);
335             }
336             // Unindexed!
337             otherText.append("(").append(qualifier).append(")");
338           }
339         } else if (encodings.contains(functionName)) {
340           otherText.append("").append(args.get(0));
341           otherIndexBuilder.addEntryWithString(indexedEntry, args.get(0), EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
342         } else if (isGender(functionName)) {
343           appendGender(otherText, functionName, args);
344         } else if (functionName.equals("g")) {
345           otherText.append("{g}");
346         } else if (functionName.equals("l")) {
347           // encodes text in various langs.
348           // lang is arg 0.
349           otherText.append("").append(args.get(1));
350           otherIndexBuilder.addEntryWithString(indexedEntry, args.get(1), EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
351           // TODO: transliteration
352         } else if (functionName.equals("term")) {
353           // cross-reference to another dictionary
354           otherText.append("").append(args.get(0));
355           otherIndexBuilder.addEntryWithString(indexedEntry, args.get(0), EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
356           // TODO: transliteration
357         } else if (functionName.equals("italbrac") || functionName.equals("gloss")) {
358           // TODO: put this text aside to use it.
359           otherText.append("[").append(args.get(0)).append("]");
360           otherIndexBuilder.addEntryWithString(indexedEntry, args.get(0), EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
361         } else if (functionName.equals("ttbc")) {
362           LOG.warning("Unexpected {{ttbc}}");
363         } else if (functionName.equals("trreq")) {
364         } else if (functionName.equals("not used")) {
365           otherText.append("(not used)");
366         } else if (functionName.equals("t-image")) {
367           // American sign language
368         } else {
369           // Unindexed!
370           otherText.append(wikiTokenizer.token());
371         }
372         
373       } else if (wikiTokenizer.isNewline()) {
374         assert false;
375       } else if (wikiTokenizer.isComment()) {
376       } else if (wikiTokenizer.isMarkup()) {
377       } else {
378         LOG.warning("Bad translation token: " + wikiTokenizer.token());
379       }
380     }
381     if (otherText.length() == 0) {
382       LOG.warning("Empty otherText: " + line);
383       return;
384     }
385     
386     if (lang != null) {
387       otherText.insert(0, String.format("(%s) ", lang));
388     }
389     
390     StringBuilder englishText = new StringBuilder();
391     
392     englishText.append(title);
393     if (sense != null) {
394       englishText.append(" (").append(sense).append(")");
395       enIndexBuilder.addEntryWithString(indexedEntry, sense, EntryTypeName.WIKTIONARY_TRANSLATION_SENSE, EntryTypeName.WIKTIONARY_TRANSLATION_SENSE);
396     }
397     if (pos != null) {
398       englishText.append(" (").append(pos.toLowerCase()).append(")");
399     }
400     enIndexBuilder.addEntryWithString(indexedEntry, title, EntryTypeName.WIKTIONARY_TITLE_SINGLE, EntryTypeName.WIKTIONARY_TITLE_MULTI);
401     
402     final Pair pair = new Pair(trim(englishText.toString()), trim(otherText.toString()), swap);
403     pairEntry.pairs.add(pair);
404     if (!pairsAdded.add(pair.toString())) {
405       LOG.warning("Duplicate pair: " + pair.toString());
406     }
407     if (pair.toString().equals("libero {m} :: free (adjective)")) {
408       System.out.println();
409     }
410
411   }
412
413
414   private void appendGender(final StringBuilder otherText,
415       final String functionName, final List<String> args) {
416     otherText.append("{");
417     otherText.append(functionName);
418     for (int i = 0; i < args.size(); ++i) {
419       otherText.append("|").append(args.get(i));
420     }
421     otherText.append("}");
422   }
423
424
425   private boolean isGender(final String functionName) {
426     return functionName.equals("m") || functionName.equals("f") || functionName.equals("n") || functionName.equals("p");
427   }
428   
429   Set<String> pairsAdded = new LinkedHashSet<String>();
430   
431   // -------------------------------------------------------------------------
432   
433   private void doForeignWord(final String lang, final String title, final String text) {
434     final WikiTokenizer wikiTokenizer = new WikiTokenizer(text);
435     while (wikiTokenizer.nextToken() != null) {
436       if (wikiTokenizer.isHeading()) {
437         final String headingName = wikiTokenizer.headingWikiText();
438         if (headingName.equals("Translations")) {
439           LOG.warning("Translations not in English section: " + title);
440         } else if (headingName.equals("Pronunciation")) {
441           //doPronunciation(wikiLineReader);
442         } else if (partOfSpeechHeader.matcher(headingName).matches()) {
443           doForeignPartOfSpeech(lang, title, headingName, wikiTokenizer.headingDepth(), wikiTokenizer);
444         }
445       } else {
446       }
447     }
448   }
449   
450   static final class ListSection {
451     final String firstPrefix;
452     final String firstLine;
453     final List<String> nextPrefixes = new ArrayList<String>();
454     final List<String> nextLines = new ArrayList<String>();
455     
456     public ListSection(String firstPrefix, String firstLine) {
457       this.firstPrefix = firstPrefix;
458       this.firstLine = firstLine;
459     }
460
461     @Override
462     public String toString() {
463       return firstPrefix + firstLine + "{ " + nextPrefixes + "}";
464     }
465   }
466
467
468   int foreignCount = 0;
469   private void doForeignPartOfSpeech(final String lang, String title, final String posHeading, final int posDepth, WikiTokenizer wikiTokenizer) {
470     if (++foreignCount % 1000 == 0) {
471       LOG.info("***" + lang + ", " + title + ", pos=" + posHeading + ", foreignCount=" + foreignCount);
472     }
473     if (title.equals("moro")) {
474       System.out.println();
475     }
476     
477     final StringBuilder foreignBuilder = new StringBuilder();
478     final Collection<String> wordForms = new ArrayList<String>();
479     final List<ListSection> listSections = new ArrayList<ListSection>();
480     
481     try {
482     
483     ListSection lastListSection = null;
484     
485     int currentHeadingDepth = posDepth;
486     while (wikiTokenizer.nextToken() != null) {
487       if (wikiTokenizer.isHeading()) {
488         currentHeadingDepth = wikiTokenizer.headingDepth();
489         
490         if (currentHeadingDepth <= posDepth) {
491           wikiTokenizer.returnToLineStart();
492           return;
493         }
494       }
495       
496       if (currentHeadingDepth > posDepth) {
497         // TODO: deal with other neat info sections
498         continue;
499       }
500       
501       if (wikiTokenizer.isFunction()) {
502         final String name = wikiTokenizer.functionName();
503         final List<String> args = wikiTokenizer.functionPositionArgs();
504         final Map<String,String> namedArgs = wikiTokenizer.functionNamedArgs();
505         // First line is generally a repeat of the title with some extra information.
506         // We need to build up the left side (foreign text, tokens) separately from the
507         // right side (English).  The left-side may get paired with multiple right sides.
508         // The left side should get filed under every form of the word in question (singular, plural).
509         
510         // For verbs, the conjugation comes later on in a deeper section.
511         // Ideally, we'd want to file every English entry with the verb
512         // under every verb form coming from the conjugation.
513         // Ie. under "fa": see: "make :: fare" and "do :: fare"
514         // But then where should we put the conjugation table?
515         // 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!)
516         // for the conjugation table from "fa".
517         // Would like to be able to link to a lang#token.
518       if (isGender(name)) {
519         appendGender(foreignBuilder, name, args);
520       } else if (name.equals("wikipedia")) {
521         namedArgs.remove("lang");
522         if (args.size() > 1 || !namedArgs.isEmpty()) {
523           // Unindexed!
524           foreignBuilder.append(wikiTokenizer.token());
525         } else if (args.size() == 1) {
526           foreignBuilder.append(wikiTokenizer.token());
527         } else {
528           //foreignBuilder.append(title);
529         }
530       } else if (name.equals("attention") || name.equals("zh-attention")) {
531         // See: http://en.wiktionary.org/wiki/Template:attention
532         // Ignore these.
533       } else if (name.equals("infl")) {
534         // See: http://en.wiktionary.org/wiki/Template:infl
535         final String langCode = get(args, 0);
536         namedArgs.remove("sc");
537         final String tr = namedArgs.remove("tr");
538         final String g = namedArgs.remove("g");
539         final String g2 = namedArgs.remove("g2");
540         final String g3 = namedArgs.remove("g3");
541         if (!namedArgs.isEmpty()) {
542           LOG.warning("Didn't parse infl: " + wikiTokenizer.token());
543           foreignBuilder.append(wikiTokenizer.token());
544         } else {
545           String head = namedArgs.get("head");
546           if (head == null) {
547             head = title;
548           } else {
549             head = WikiTokenizer.toPlainText(head);
550           }
551           foreignBuilder.append(head);
552     
553           if (g != null) {
554             foreignBuilder.append(" {").append(g);
555             if (g2 != null) {
556               foreignBuilder.append("|").append(g2);
557             }
558             if (g3 != null) {
559               foreignBuilder.append("|").append(g3);
560             }
561             foreignBuilder.append("}");
562           }
563     
564           if (tr != null) {
565             foreignBuilder.append(String.format(TRANSLITERATION_FORMAT, tr));
566             wordForms.add(tr);
567           }
568     
569           final String pos = get(args, 1);
570           if (pos != null) {
571             foreignBuilder.append(" (").append(pos).append(")");
572           }
573           for (int i = 2; i < args.size(); i += 2) {
574             final String inflName = get(args, i);
575             final String inflValue = get(args, i + 1);
576             foreignBuilder.append(", ").append(WikiTokenizer.toPlainText(inflName));
577             if (inflValue != null && inflValue.length() > 0) {
578               foreignBuilder.append(": ").append(WikiTokenizer.toPlainText(inflValue));
579               wordForms.add(inflValue);
580             }
581           }
582         }
583       } else if (name.equals("it-noun")) {
584           final String base = get(args, 0);
585           final String gender = get(args, 1);
586           final String singular = base + get(args, 2);
587           final String plural = base + get(args, 3);
588           foreignBuilder.append(String.format(" %s {%s}, %s {pl}", singular, gender, plural, plural));
589           wordForms.add(singular);
590           wordForms.add(plural);
591         } else if (name.equals("it-proper noun")) {
592           foreignBuilder.append(wikiTokenizer.token());
593         } else if (name.equals("it-adj")) {
594           foreignBuilder.append(wikiTokenizer.token());
595         } else if (name.startsWith("it-conj")) {
596           if (name.equals("it-conj-are")) {
597             itConjAre(args, namedArgs);
598           } else if (name.equals("it-conj-ere")) {
599           } else if (name.equals("it-conj-ire")) {
600           } else {
601             LOG.warning("Unknown conjugation: " + wikiTokenizer.token());
602           }
603         } else {
604           // Unindexed!
605           foreignBuilder.append(wikiTokenizer.token());
606           // LOG.warning("Unknown function: " + wikiTokenizer.token());
607         }
608         
609       } else if (wikiTokenizer.isListItem()) {
610         final String prefix = wikiTokenizer.listItemPrefix();
611         if (lastListSection != null && 
612             prefix.startsWith(lastListSection.firstPrefix) && 
613             prefix.length() > lastListSection.firstPrefix.length()) {
614           lastListSection.nextPrefixes.add(prefix);
615           lastListSection.nextLines.add(wikiTokenizer.listItemWikiText());
616         } else {
617           lastListSection = new ListSection(prefix, wikiTokenizer.listItemWikiText());
618           listSections.add(lastListSection);
619         }
620       } else if (lastListSection != null) {
621         // Don't append anything after the lists, because there's crap.
622       } else if (wikiTokenizer.isWikiLink()) {
623         // Unindexed!
624         foreignBuilder.append(wikiTokenizer.wikiLinkText());
625         
626       } else if (wikiTokenizer.isPlainText()) {
627         // Unindexed!
628         foreignBuilder.append(wikiTokenizer.token());
629         
630       } else if (wikiTokenizer.isMarkup() || wikiTokenizer.isNewline() || wikiTokenizer.isComment()) {
631         // Do nothing.
632       } else {
633         LOG.warning("Unexpected token: " + wikiTokenizer.token());
634       }
635     }
636     
637     } finally {
638       // Here's where we exit.
639       // Should we make an entry even if there are no foreign list items?
640       String foreign = foreignBuilder.toString().trim();
641       if (!foreign.toLowerCase().startsWith(title.toLowerCase())) {
642         foreign = String.format("%s %s", title, foreign);
643       }
644       if (!langPattern.matcher(lang).matches()) {
645         foreign = String.format("(%s) %s", lang, foreign);
646       }
647       for (final ListSection listSection : listSections) {
648         doForeignListItem(foreign, title, wordForms, listSection);
649       }
650     }
651   }
652   
653   
654   static final Pattern UNINDEXED_WIKI_TEXT = Pattern.compile(
655       "(first|second|third)-person (singular|plural)|" +
656       "present tense|" +
657       "imperative"
658       );
659
660
661   private void doForeignListItem(final String foreignText, String title, final Collection<String> forms, final ListSection listSection) {
662     
663     final String prefix = listSection.firstPrefix;
664     if (prefix.length() > 1) {
665       // Could just get looser and say that any prefix longer than first is a sublist.
666       LOG.warning("Prefix too long: " + listSection);
667       return;
668     }
669     
670     final PairEntry pairEntry = new PairEntry();
671     final IndexedEntry indexedEntry = new IndexedEntry(pairEntry);
672     
673     final StringBuilder englishBuilder = new StringBuilder();
674
675     final String mainLine = listSection.firstLine;
676     
677     final WikiTokenizer englishTokenizer = new WikiTokenizer(mainLine, false);
678     while (englishTokenizer.nextToken() != null) {
679       // TODO handle form of....
680       if (englishTokenizer.isPlainText()) {
681         englishBuilder.append(englishTokenizer.token());
682         enIndexBuilder.addEntryWithString(indexedEntry, englishTokenizer.token(), EntryTypeName.WIKTIONARY_ENGLISH_DEF);
683       } else if (englishTokenizer.isWikiLink()) {
684         final String text = englishTokenizer.wikiLinkText();
685         final String link = englishTokenizer.wikiLinkDest();
686         if (link != null) {
687           if (link.contains("#English")) {
688             englishBuilder.append(text);
689             enIndexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_ENGLISH_DEF_WIKI_LINK);
690           } else if (link.contains("#") && this.langPattern.matcher(link).find()) {
691             englishBuilder.append(text);
692             otherIndexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_ENGLISH_DEF_OTHER_LANG);
693           } else if (link.equals("plural")) {
694             englishBuilder.append(text);
695           } else {
696             //LOG.warning("Special link: " + englishTokenizer.token());
697             enIndexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_ENGLISH_DEF_WIKI_LINK);
698             englishBuilder.append(text);
699           }
700         } else {
701           // link == null
702           englishBuilder.append(text);
703           if (!UNINDEXED_WIKI_TEXT.matcher(text).find()) {
704             enIndexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_ENGLISH_DEF_WIKI_LINK);
705           }
706         }
707       } else if (englishTokenizer.isFunction()) {
708         final String name = englishTokenizer.functionName();
709         if (name.contains("conjugation of ") || 
710             name.contains("form of ") || 
711             name.contains("feminine of ") || 
712             name.contains("plural of ")) {
713           // Ignore these in the index, they're really annoying....
714           englishBuilder.append(englishTokenizer.token());
715         } else {
716           englishBuilder.append(englishTokenizer.token());
717 //          LOG.warning("Unexpected function: " + englishTokenizer.token());
718         }
719       } else {
720         if (englishTokenizer.isComment() || englishTokenizer.isMarkup()) {
721         } else {
722           LOG.warning("Unexpected definition text: " + englishTokenizer.token());
723         }
724       }
725     }
726         
727     final String english = trim(englishBuilder.toString());
728     if (english.length() > 0) {
729       final Pair pair = new Pair(english, trim(foreignText), this.swap);
730       pairEntry.pairs.add(pair);
731       otherIndexBuilder.addEntryWithString(indexedEntry, title, EntryTypeName.WIKTIONARY_TITLE_SINGLE, EntryTypeName.WIKTIONARY_TITLE_MULTI);
732       for (final String form : forms) {
733         otherIndexBuilder.addEntryWithString(indexedEntry, form, EntryTypeName.WIKTIONARY_FORM_SINGLE, EntryTypeName.WIKTIONARY_FORM_MULTI);
734       }
735     }
736     
737     // Do examples.
738     String lastForeign = null;
739     for (int i = 0; i < listSection.nextPrefixes.size(); ++i) {
740       final String nextPrefix = listSection.nextPrefixes.get(i);
741       final String nextLine = listSection.nextLines.get(i);
742       int dash = nextLine.indexOf("&mdash;");
743       int mdashLen = 7;
744       if (dash == -1) {
745         dash = nextLine.indexOf("—");
746         mdashLen = 1;
747       }
748       if (dash == -1) {
749         dash = nextLine.indexOf(" - ");
750         mdashLen = 3;
751       }
752       
753       if ((nextPrefix.equals("#:") || nextPrefix.equals("##:")) && dash != -1) {
754         final String foreignEx = nextLine.substring(0, dash);
755         final String englishEx = nextLine.substring(dash + mdashLen);
756         final Pair pair = new Pair(formatAndIndexExampleString(englishEx, enIndexBuilder, indexedEntry), formatAndIndexExampleString(foreignEx, otherIndexBuilder, indexedEntry), swap);
757         if (pair.lang1 != "--" && pair.lang1 != "--") {
758           pairEntry.pairs.add(pair);
759         }
760         lastForeign = null;
761       } else if (nextPrefix.equals("#:") || nextPrefix.equals("##:")){
762         final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
763         lastForeign = nextLine;
764         if (pair.lang1 != "--" && pair.lang1 != "--") {
765           pairEntry.pairs.add(pair);
766         }
767       } else if (nextPrefix.equals("#::") || nextPrefix.equals("#**")) {
768         if (lastForeign != null && pairEntry.pairs.size() > 0) {
769           pairEntry.pairs.remove(pairEntry.pairs.size() - 1);
770           final Pair pair = new Pair(formatAndIndexExampleString(nextLine, enIndexBuilder, indexedEntry), formatAndIndexExampleString(lastForeign, otherIndexBuilder, indexedEntry), swap);
771           if (pair.lang1 != "--" && pair.lang1 != "--") {
772             pairEntry.pairs.add(pair);
773           }
774           lastForeign = null;
775         } else {
776           LOG.warning("TODO: English example with no foreign: " + title + ", " + nextLine);
777           // TODO: add something.
778         }
779       } else if (nextPrefix.equals("#*")) {
780         // Can't really index these.
781         final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
782         lastForeign = nextLine;
783         if (pair.lang1 != "--" && pair.lang1 != "--") {
784           pairEntry.pairs.add(pair);
785         }
786       } else if (nextPrefix.equals("#::*") || nextPrefix.equals("##") || nextPrefix.equals("#*:") || nextPrefix.equals("#:*") || true) {
787         final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
788         if (pair.lang1 != "--" && pair.lang1 != "--") {
789           pairEntry.pairs.add(pair);
790         }
791 //      } else {
792 //        assert false;
793       }
794     }
795   }
796   
797   private String formatAndIndexExampleString(final String example, final IndexBuilder indexBuilder, final IndexedEntry indexedEntry) {
798     final WikiTokenizer wikiTokenizer = new WikiTokenizer(example, false);
799     final StringBuilder builder = new StringBuilder();
800     boolean insideTripleQuotes = false;
801     while (wikiTokenizer.nextToken() != null) {
802       if (wikiTokenizer.isPlainText()) {
803         builder.append(wikiTokenizer.token());
804         if (indexBuilder != null) {
805           indexBuilder.addEntryWithString(indexedEntry, wikiTokenizer.token(), EntryTypeName.WIKTIONARY_EXAMPLE);
806         }
807       } else if (wikiTokenizer.isWikiLink()) {
808         final String text = wikiTokenizer.wikiLinkText().replaceAll("'", ""); 
809         builder.append(text);
810         if (indexBuilder != null) {
811           indexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_EXAMPLE);
812         }
813       } else if (wikiTokenizer.isFunction()) {
814         builder.append(wikiTokenizer.token());
815       } else if (wikiTokenizer.isMarkup()) {
816         if (wikiTokenizer.token().equals("'''")) {
817           insideTripleQuotes = !insideTripleQuotes;
818         }
819       } else if (wikiTokenizer.isComment() || wikiTokenizer.isNewline()) {
820         // Do nothing.
821       } else {
822         LOG.warning("unexpected token: " + wikiTokenizer.token());
823       }
824     }
825     final String result = trim(builder.toString());
826     return result.length() > 0 ? result : "--";
827   }
828
829
830   private void itConjAre(List<String> args, Map<String, String> namedArgs) {
831     final String base = args.get(0);
832     final String aux = args.get(1);
833     
834     putIfMissing(namedArgs, "inf", base + "are");
835     putIfMissing(namedArgs, "aux", aux);
836     putIfMissing(namedArgs, "ger", base + "ando");
837     putIfMissing(namedArgs, "presp", base + "ante");
838     putIfMissing(namedArgs, "pastp", base + "ato");
839     // Present
840     putIfMissing(namedArgs, "pres1s", base + "o");
841     putIfMissing(namedArgs, "pres2s", base + "i");
842     putIfMissing(namedArgs, "pres3s", base + "a");
843     putIfMissing(namedArgs, "pres1p", base + "iamo");
844     putIfMissing(namedArgs, "pres2p", base + "ate");
845     putIfMissing(namedArgs, "pres3p", base + "ano");
846     // Imperfect
847     putIfMissing(namedArgs, "imperf1s", base + "avo");
848     putIfMissing(namedArgs, "imperf2s", base + "avi");
849     putIfMissing(namedArgs, "imperf3s", base + "ava");
850     putIfMissing(namedArgs, "imperf1p", base + "avamo");
851     putIfMissing(namedArgs, "imperf2p", base + "avate");
852     putIfMissing(namedArgs, "imperf3p", base + "avano");
853     // Passato remoto
854     putIfMissing(namedArgs, "prem1s", base + "ai");
855     putIfMissing(namedArgs, "prem2s", base + "asti");
856     putIfMissing(namedArgs, "prem3s", base + "ò");
857     putIfMissing(namedArgs, "prem1p", base + "ammo");
858     putIfMissing(namedArgs, "prem2p", base + "aste");
859     putIfMissing(namedArgs, "prem3p", base + "arono");
860     // Future
861     putIfMissing(namedArgs, "fut1s", base + "erò");
862     putIfMissing(namedArgs, "fut2s", base + "erai");
863     putIfMissing(namedArgs, "fut3s", base + "erà");
864     putIfMissing(namedArgs, "fut1p", base + "eremo");
865     putIfMissing(namedArgs, "fut2p", base + "erete");
866     putIfMissing(namedArgs, "fut3p", base + "eranno");
867     // Conditional
868     putIfMissing(namedArgs, "cond1s", base + "erei");
869     putIfMissing(namedArgs, "cond2s", base + "eresti");
870     putIfMissing(namedArgs, "cond3s", base + "erebbe");
871     putIfMissing(namedArgs, "cond1p", base + "eremmo");
872     putIfMissing(namedArgs, "cond2p", base + "ereste");
873     putIfMissing(namedArgs, "cond3p", base + "erebbero");
874     // Subjunctive / congiuntivo
875     putIfMissing(namedArgs, "sub123s", base + "i");
876     putIfMissing(namedArgs, "sub1p", base + "iamo");
877     putIfMissing(namedArgs, "sub2p", base + "iate");
878     putIfMissing(namedArgs, "sub3p", base + "ino");
879     // Imperfect subjunctive
880     putIfMissing(namedArgs, "impsub12s", base + "assi");
881     putIfMissing(namedArgs, "impsub3s", base + "asse");
882     putIfMissing(namedArgs, "impsub1p", base + "assimo");
883     putIfMissing(namedArgs, "impsub2p", base + "aste");
884     putIfMissing(namedArgs, "impsub3p", base + "assero");
885     // Imperative
886     putIfMissing(namedArgs, "imp2s", base + "a");
887     putIfMissing(namedArgs, "imp3s", base + "i");
888     putIfMissing(namedArgs, "imp1p", base + "iamo");
889     putIfMissing(namedArgs, "imp2p", base + "ate");
890     putIfMissing(namedArgs, "imp3p", base + "ino");
891
892
893     itConj(args, namedArgs);
894   }
895
896
897   private void itConj(List<String> args, Map<String, String> namedArgs) {
898     // TODO Auto-generated method stub
899     
900   }
901
902
903   private static void putIfMissing(final Map<String, String> namedArgs, final String key,
904       final String value) {
905     final String oldValue = namedArgs.get(key);
906     if (oldValue == null || oldValue.length() == 0) {
907       namedArgs.put(key, value);
908     }
909   }
910   
911   // TODO: check how ='' and =| are manifested....
912   // TODO: get this right in -are
913   private static void putOrNullify(final Map<String, String> namedArgs, final String key,
914       final String value) {
915     final String oldValue = namedArgs.get(key);
916     if (oldValue == null/* || oldValue.length() == 0*/) {
917       namedArgs.put(key, value);
918     } else {
919       if (oldValue.equals("''")) {
920         namedArgs.put(key, "");
921       }
922     }
923   }
924
925   static final Pattern whitespace = Pattern.compile("\\s+");
926   static String trim(final String s) {
927     return whitespace.matcher(s).replaceAll(" ").trim();
928   }
929
930   
931 }