]> gitweb.fperrin.net Git - DictionaryPC.git/blob - src/com/hughes/android/dictionary/parser/EnWiktionaryXmlParser.java
86d0ddc05b4fb44f967da9f2df1ced0f2c242906
[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     boolean titleAppended = false;
478     final StringBuilder foreignBuilder = new StringBuilder();
479     final Collection<String> wordForms = new ArrayList<String>();
480     final List<ListSection> listSections = new ArrayList<ListSection>();
481     
482     try {
483     
484     ListSection lastListSection = null;
485     
486     int currentHeadingDepth = posDepth;
487     while (wikiTokenizer.nextToken() != null) {
488       if (wikiTokenizer.isHeading()) {
489         currentHeadingDepth = wikiTokenizer.headingDepth();
490         
491         if (currentHeadingDepth <= posDepth) {
492           wikiTokenizer.returnToLineStart();
493           return;
494         }
495       }
496       
497       if (currentHeadingDepth > posDepth) {
498         // TODO: deal with other neat info sections
499         continue;
500       }
501       
502       if (wikiTokenizer.isFunction()) {
503         final String name = wikiTokenizer.functionName();
504         final List<String> args = wikiTokenizer.functionPositionArgs();
505         final Map<String,String> namedArgs = wikiTokenizer.functionNamedArgs();
506         // First line is generally a repeat of the title with some extra information.
507         // We need to build up the left side (foreign text, tokens) separately from the
508         // right side (English).  The left-side may get paired with multiple right sides.
509         // The left side should get filed under every form of the word in question (singular, plural).
510         
511         // For verbs, the conjugation comes later on in a deeper section.
512         // Ideally, we'd want to file every English entry with the verb
513         // under every verb form coming from the conjugation.
514         // Ie. under "fa": see: "make :: fare" and "do :: fare"
515         // But then where should we put the conjugation table?
516         // 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!)
517         // for the conjugation table from "fa".
518         // Would like to be able to link to a lang#token.
519       if (isGender(name)) {
520         appendGender(foreignBuilder, name, args);
521       } else if (name.equals("wikipedia")) {
522         namedArgs.remove("lang");
523         if (args.size() > 1 || !namedArgs.isEmpty()) {
524           // Unindexed!
525           foreignBuilder.append(wikiTokenizer.token());
526         } else if (args.size() == 1) {
527           foreignBuilder.append(wikiTokenizer.token());
528         } else {
529           //foreignBuilder.append(title);
530         }
531       } else if (name.equals("attention") || name.equals("zh-attention")) {
532         // See: http://en.wiktionary.org/wiki/Template:attention
533         // Ignore these.
534       } else if (name.equals("infl")) {
535         // See: http://en.wiktionary.org/wiki/Template:infl
536         final String langCode = get(args, 0);
537         String head = namedArgs.remove("head");
538         if (head == null) {
539           head = namedArgs.remove("title"); // Bug
540         }
541         if (head == null) {
542           head = title;
543         } else {
544           head = WikiTokenizer.toPlainText(head);
545         }
546         titleAppended = true;
547         
548         namedArgs.remove("sc");
549         namedArgs.remove("lang");
550         namedArgs.remove("sort");
551         namedArgs.remove("cat");
552
553         final String tr = namedArgs.remove("tr");
554         String g = namedArgs.remove("g");
555         if (g == null) {
556           g = namedArgs.remove("gender");
557         }
558         final String g2 = namedArgs.remove("g2");
559         final String g3 = namedArgs.remove("g3");
560
561         foreignBuilder.append(head);
562   
563         if (g != null) {
564           foreignBuilder.append(" {").append(g);
565           if (g2 != null) {
566             foreignBuilder.append("|").append(g2);
567           }
568           if (g3 != null) {
569             foreignBuilder.append("|").append(g3);
570           }
571           foreignBuilder.append("}");
572         }
573   
574         if (tr != null) {
575           foreignBuilder.append(String.format(TRANSLITERATION_FORMAT, tr));
576           wordForms.add(tr);
577         }
578   
579         final String pos = get(args, 1);
580         if (pos != null) {
581           foreignBuilder.append(" (").append(pos).append(")");
582         }
583         for (int i = 2; i < args.size(); i += 2) {
584           final String inflName = get(args, i);
585           final String inflValue = get(args, i + 1);
586           foreignBuilder.append(", ").append(WikiTokenizer.toPlainText(inflName));
587           if (inflValue != null && inflValue.length() > 0) {
588             foreignBuilder.append(": ").append(WikiTokenizer.toPlainText(inflValue));
589             wordForms.add(inflValue);
590           }
591         }
592         for (final String key : namedArgs.keySet()) {
593           final String value = WikiTokenizer.toPlainText(namedArgs.get(key));
594           foreignBuilder.append(" ").append(key).append("=").append(value);
595           wordForms.add(value);
596         }
597       } else if (name.equals("it-noun")) {
598         titleAppended = true;
599         final String base = get(args, 0);
600         final String gender = get(args, 1);
601         final String singular = base + get(args, 2);
602         final String plural = base + get(args, 3);
603         foreignBuilder.append(String.format(" %s {%s}, %s {pl}", singular, gender, plural, plural));
604         wordForms.add(singular);
605         wordForms.add(plural);
606         } else if (name.equals("it-proper noun")) {
607           foreignBuilder.append(wikiTokenizer.token());
608         } else if (name.equals("it-adj")) {
609           foreignBuilder.append(wikiTokenizer.token());
610         } else if (name.startsWith("it-conj")) {
611           if (name.equals("it-conj-are")) {
612             itConjAre(args, namedArgs);
613           } else if (name.equals("it-conj-ere")) {
614           } else if (name.equals("it-conj-ire")) {
615           } else {
616             LOG.warning("Unknown conjugation: " + wikiTokenizer.token());
617           }
618         } else {
619           // Unindexed!
620           foreignBuilder.append(wikiTokenizer.token());
621           // LOG.warning("Unknown function: " + wikiTokenizer.token());
622         }
623         
624       } else if (wikiTokenizer.isListItem()) {
625         final String prefix = wikiTokenizer.listItemPrefix();
626         if (lastListSection != null && 
627             prefix.startsWith(lastListSection.firstPrefix) && 
628             prefix.length() > lastListSection.firstPrefix.length()) {
629           lastListSection.nextPrefixes.add(prefix);
630           lastListSection.nextLines.add(wikiTokenizer.listItemWikiText());
631         } else {
632           lastListSection = new ListSection(prefix, wikiTokenizer.listItemWikiText());
633           listSections.add(lastListSection);
634         }
635       } else if (lastListSection != null) {
636         // Don't append anything after the lists, because there's crap.
637       } else if (wikiTokenizer.isWikiLink()) {
638         // Unindexed!
639         foreignBuilder.append(wikiTokenizer.wikiLinkText());
640         
641       } else if (wikiTokenizer.isPlainText()) {
642         // Unindexed!
643         foreignBuilder.append(wikiTokenizer.token());
644         
645       } else if (wikiTokenizer.isMarkup() || wikiTokenizer.isNewline() || wikiTokenizer.isComment()) {
646         // Do nothing.
647       } else {
648         LOG.warning("Unexpected token: " + wikiTokenizer.token());
649       }
650     }
651     
652     } finally {
653       // Here's where we exit.
654       // Should we make an entry even if there are no foreign list items?
655       String foreign = foreignBuilder.toString().trim();
656       if (!titleAppended && !foreign.toLowerCase().startsWith(title.toLowerCase())) {
657         foreign = String.format("%s %s", title, foreign);
658       }
659       if (!langPattern.matcher(lang).matches()) {
660         foreign = String.format("(%s) %s", lang, foreign);
661       }
662       for (final ListSection listSection : listSections) {
663         doForeignListItem(foreign, title, wordForms, listSection);
664       }
665     }
666   }
667   
668   
669   static final Pattern UNINDEXED_WIKI_TEXT = Pattern.compile(
670       "(first|second|third)-person (singular|plural)|" +
671       "present tense|" +
672       "imperative"
673       );
674
675
676   private void doForeignListItem(final String foreignText, String title, final Collection<String> forms, final ListSection listSection) {
677     
678     final String prefix = listSection.firstPrefix;
679     if (prefix.length() > 1) {
680       // Could just get looser and say that any prefix longer than first is a sublist.
681       LOG.warning("Prefix too long: " + listSection);
682       return;
683     }
684     
685     final PairEntry pairEntry = new PairEntry();
686     final IndexedEntry indexedEntry = new IndexedEntry(pairEntry);
687     
688     final StringBuilder englishBuilder = new StringBuilder();
689
690     final String mainLine = listSection.firstLine;
691     
692     final WikiTokenizer englishTokenizer = new WikiTokenizer(mainLine, false);
693     while (englishTokenizer.nextToken() != null) {
694       // TODO handle form of....
695       if (englishTokenizer.isPlainText()) {
696         englishBuilder.append(englishTokenizer.token());
697         enIndexBuilder.addEntryWithString(indexedEntry, englishTokenizer.token(), EntryTypeName.WIKTIONARY_ENGLISH_DEF);
698       } else if (englishTokenizer.isWikiLink()) {
699         final String text = englishTokenizer.wikiLinkText();
700         final String link = englishTokenizer.wikiLinkDest();
701         if (link != null) {
702           if (link.contains("#English")) {
703             englishBuilder.append(text);
704             enIndexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_ENGLISH_DEF_WIKI_LINK);
705           } else if (link.contains("#") && this.langPattern.matcher(link).find()) {
706             englishBuilder.append(text);
707             otherIndexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_ENGLISH_DEF_OTHER_LANG);
708           } else if (link.equals("plural")) {
709             englishBuilder.append(text);
710           } else {
711             //LOG.warning("Special link: " + englishTokenizer.token());
712             enIndexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_ENGLISH_DEF_WIKI_LINK);
713             englishBuilder.append(text);
714           }
715         } else {
716           // link == null
717           englishBuilder.append(text);
718           if (!UNINDEXED_WIKI_TEXT.matcher(text).find()) {
719             enIndexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_ENGLISH_DEF_WIKI_LINK);
720           }
721         }
722       } else if (englishTokenizer.isFunction()) {
723         final String name = englishTokenizer.functionName();
724         if (name.contains("conjugation of ") || 
725             name.contains("form of ") || 
726             name.contains("feminine of ") || 
727             name.contains("plural of ")) {
728           // Ignore these in the index, they're really annoying....
729           englishBuilder.append(englishTokenizer.token());
730         } else {
731           englishBuilder.append(englishTokenizer.token());
732 //          LOG.warning("Unexpected function: " + englishTokenizer.token());
733         }
734       } else {
735         if (englishTokenizer.isComment() || englishTokenizer.isMarkup()) {
736         } else {
737           LOG.warning("Unexpected definition text: " + englishTokenizer.token());
738         }
739       }
740     }
741         
742     final String english = trim(englishBuilder.toString());
743     if (english.length() > 0) {
744       final Pair pair = new Pair(english, trim(foreignText), this.swap);
745       pairEntry.pairs.add(pair);
746       otherIndexBuilder.addEntryWithString(indexedEntry, title, EntryTypeName.WIKTIONARY_TITLE_SINGLE, EntryTypeName.WIKTIONARY_TITLE_MULTI);
747       for (final String form : forms) {
748         otherIndexBuilder.addEntryWithString(indexedEntry, form, EntryTypeName.WIKTIONARY_FORM_SINGLE, EntryTypeName.WIKTIONARY_FORM_MULTI);
749       }
750     }
751     
752     // Do examples.
753     String lastForeign = null;
754     for (int i = 0; i < listSection.nextPrefixes.size(); ++i) {
755       final String nextPrefix = listSection.nextPrefixes.get(i);
756       final String nextLine = listSection.nextLines.get(i);
757       int dash = nextLine.indexOf("&mdash;");
758       int mdashLen = 7;
759       if (dash == -1) {
760         dash = nextLine.indexOf("—");
761         mdashLen = 1;
762       }
763       if (dash == -1) {
764         dash = nextLine.indexOf(" - ");
765         mdashLen = 3;
766       }
767       
768       if ((nextPrefix.equals("#:") || nextPrefix.equals("##:")) && dash != -1) {
769         final String foreignEx = nextLine.substring(0, dash);
770         final String englishEx = nextLine.substring(dash + mdashLen);
771         final Pair pair = new Pair(formatAndIndexExampleString(englishEx, enIndexBuilder, indexedEntry), formatAndIndexExampleString(foreignEx, otherIndexBuilder, indexedEntry), swap);
772         if (pair.lang1 != "--" && pair.lang1 != "--") {
773           pairEntry.pairs.add(pair);
774         }
775         lastForeign = null;
776       } else if (nextPrefix.equals("#:") || nextPrefix.equals("##:")){
777         final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
778         lastForeign = nextLine;
779         if (pair.lang1 != "--" && pair.lang1 != "--") {
780           pairEntry.pairs.add(pair);
781         }
782       } else if (nextPrefix.equals("#::") || nextPrefix.equals("#**")) {
783         if (lastForeign != null && pairEntry.pairs.size() > 0) {
784           pairEntry.pairs.remove(pairEntry.pairs.size() - 1);
785           final Pair pair = new Pair(formatAndIndexExampleString(nextLine, enIndexBuilder, indexedEntry), formatAndIndexExampleString(lastForeign, otherIndexBuilder, indexedEntry), swap);
786           if (pair.lang1 != "--" || pair.lang2 != "--") {
787             pairEntry.pairs.add(pair);
788           }
789           lastForeign = null;
790         } else {
791           LOG.warning("TODO: English example with no foreign: " + title + ", " + nextLine);
792           final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
793           if (pair.lang1 != "--" || pair.lang2 != "--") {
794             pairEntry.pairs.add(pair);
795           }
796         }
797       } else if (nextPrefix.equals("#*")) {
798         // Can't really index these.
799         final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
800         lastForeign = nextLine;
801         if (pair.lang1 != "--" || pair.lang2 != "--") {
802           pairEntry.pairs.add(pair);
803         }
804       } else if (nextPrefix.equals("#::*") || nextPrefix.equals("##") || nextPrefix.equals("#*:") || nextPrefix.equals("#:*") || true) {
805         final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
806         if (pair.lang1 != "--" || pair.lang2 != "--") {
807           pairEntry.pairs.add(pair);
808         }
809 //      } else {
810 //        assert false;
811       }
812     }
813   }
814   
815   private String formatAndIndexExampleString(final String example, final IndexBuilder indexBuilder, final IndexedEntry indexedEntry) {
816     final WikiTokenizer wikiTokenizer = new WikiTokenizer(example, false);
817     final StringBuilder builder = new StringBuilder();
818     boolean insideTripleQuotes = false;
819     while (wikiTokenizer.nextToken() != null) {
820       if (wikiTokenizer.isPlainText()) {
821         builder.append(wikiTokenizer.token());
822         if (indexBuilder != null) {
823           indexBuilder.addEntryWithString(indexedEntry, wikiTokenizer.token(), EntryTypeName.WIKTIONARY_EXAMPLE);
824         }
825       } else if (wikiTokenizer.isWikiLink()) {
826         final String text = wikiTokenizer.wikiLinkText().replaceAll("'", ""); 
827         builder.append(text);
828         if (indexBuilder != null) {
829           indexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_EXAMPLE);
830         }
831       } else if (wikiTokenizer.isFunction()) {
832         builder.append(wikiTokenizer.token());
833       } else if (wikiTokenizer.isMarkup()) {
834         if (wikiTokenizer.token().equals("'''")) {
835           insideTripleQuotes = !insideTripleQuotes;
836         }
837       } else if (wikiTokenizer.isComment() || wikiTokenizer.isNewline()) {
838         // Do nothing.
839       } else {
840         LOG.warning("unexpected token: " + wikiTokenizer.token());
841       }
842     }
843     final String result = trim(builder.toString());
844     return result.length() > 0 ? result : "--";
845   }
846
847
848   private void itConjAre(List<String> args, Map<String, String> namedArgs) {
849     final String base = args.get(0);
850     final String aux = args.get(1);
851     
852     putIfMissing(namedArgs, "inf", base + "are");
853     putIfMissing(namedArgs, "aux", aux);
854     putIfMissing(namedArgs, "ger", base + "ando");
855     putIfMissing(namedArgs, "presp", base + "ante");
856     putIfMissing(namedArgs, "pastp", base + "ato");
857     // Present
858     putIfMissing(namedArgs, "pres1s", base + "o");
859     putIfMissing(namedArgs, "pres2s", base + "i");
860     putIfMissing(namedArgs, "pres3s", base + "a");
861     putIfMissing(namedArgs, "pres1p", base + "iamo");
862     putIfMissing(namedArgs, "pres2p", base + "ate");
863     putIfMissing(namedArgs, "pres3p", base + "ano");
864     // Imperfect
865     putIfMissing(namedArgs, "imperf1s", base + "avo");
866     putIfMissing(namedArgs, "imperf2s", base + "avi");
867     putIfMissing(namedArgs, "imperf3s", base + "ava");
868     putIfMissing(namedArgs, "imperf1p", base + "avamo");
869     putIfMissing(namedArgs, "imperf2p", base + "avate");
870     putIfMissing(namedArgs, "imperf3p", base + "avano");
871     // Passato remoto
872     putIfMissing(namedArgs, "prem1s", base + "ai");
873     putIfMissing(namedArgs, "prem2s", base + "asti");
874     putIfMissing(namedArgs, "prem3s", base + "ò");
875     putIfMissing(namedArgs, "prem1p", base + "ammo");
876     putIfMissing(namedArgs, "prem2p", base + "aste");
877     putIfMissing(namedArgs, "prem3p", base + "arono");
878     // Future
879     putIfMissing(namedArgs, "fut1s", base + "erò");
880     putIfMissing(namedArgs, "fut2s", base + "erai");
881     putIfMissing(namedArgs, "fut3s", base + "erà");
882     putIfMissing(namedArgs, "fut1p", base + "eremo");
883     putIfMissing(namedArgs, "fut2p", base + "erete");
884     putIfMissing(namedArgs, "fut3p", base + "eranno");
885     // Conditional
886     putIfMissing(namedArgs, "cond1s", base + "erei");
887     putIfMissing(namedArgs, "cond2s", base + "eresti");
888     putIfMissing(namedArgs, "cond3s", base + "erebbe");
889     putIfMissing(namedArgs, "cond1p", base + "eremmo");
890     putIfMissing(namedArgs, "cond2p", base + "ereste");
891     putIfMissing(namedArgs, "cond3p", base + "erebbero");
892     // Subjunctive / congiuntivo
893     putIfMissing(namedArgs, "sub123s", base + "i");
894     putIfMissing(namedArgs, "sub1p", base + "iamo");
895     putIfMissing(namedArgs, "sub2p", base + "iate");
896     putIfMissing(namedArgs, "sub3p", base + "ino");
897     // Imperfect subjunctive
898     putIfMissing(namedArgs, "impsub12s", base + "assi");
899     putIfMissing(namedArgs, "impsub3s", base + "asse");
900     putIfMissing(namedArgs, "impsub1p", base + "assimo");
901     putIfMissing(namedArgs, "impsub2p", base + "aste");
902     putIfMissing(namedArgs, "impsub3p", base + "assero");
903     // Imperative
904     putIfMissing(namedArgs, "imp2s", base + "a");
905     putIfMissing(namedArgs, "imp3s", base + "i");
906     putIfMissing(namedArgs, "imp1p", base + "iamo");
907     putIfMissing(namedArgs, "imp2p", base + "ate");
908     putIfMissing(namedArgs, "imp3p", base + "ino");
909
910
911     itConj(args, namedArgs);
912   }
913
914
915   private void itConj(List<String> args, Map<String, String> namedArgs) {
916     // TODO Auto-generated method stub
917     
918   }
919
920
921   private static void putIfMissing(final Map<String, String> namedArgs, final String key,
922       final String value) {
923     final String oldValue = namedArgs.get(key);
924     if (oldValue == null || oldValue.length() == 0) {
925       namedArgs.put(key, value);
926     }
927   }
928   
929   // TODO: check how ='' and =| are manifested....
930   // TODO: get this right in -are
931   private static void putOrNullify(final Map<String, String> namedArgs, final String key,
932       final String value) {
933     final String oldValue = namedArgs.get(key);
934     if (oldValue == null/* || oldValue.length() == 0*/) {
935       namedArgs.put(key, value);
936     } else {
937       if (oldValue.equals("''")) {
938         namedArgs.put(key, "");
939       }
940     }
941   }
942
943   static final Pattern whitespace = Pattern.compile("\\s+");
944   static String trim(final String s) {
945     return whitespace.matcher(s).replaceAll(" ").trim();
946   }
947
948   
949 }