]> gitweb.fperrin.net Git - DictionaryPC.git/blob - src/com/hughes/android/dictionary/parser/EnWiktionaryXmlParser.java
Better {{form of}} handling, remove "lang=..."
[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, final T defaultValue) {
278     return index < list.size() ? list.get(index) : defaultValue;
279   }
280
281   private static <T> T get(final List<T> list, final int index) {
282     return get(list, index, null);
283   }
284
285   private static <T> T remove(final List<T> list, final int index, final T defaultValue) {
286     return index < list.size() ? list.remove(index) : defaultValue;
287   }
288
289   private void doTranslationLine(final String line, final String lang, final String title, final String pos, final String sense, final String rest) {
290     // Good chance we'll actually file this one...
291     final PairEntry pairEntry = new PairEntry();
292     final IndexedEntry indexedEntry = new IndexedEntry(pairEntry);
293     
294     final StringBuilder otherText = new StringBuilder();
295     final WikiTokenizer wikiTokenizer = new WikiTokenizer(rest, false);
296     while (wikiTokenizer.nextToken() != null) {
297       
298       if (wikiTokenizer.isPlainText()) {
299         final String plainText = wikiTokenizer.token(); 
300         otherText.append("").append(plainText);
301         otherIndexBuilder.addEntryWithString(indexedEntry, plainText, EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
302         
303       } else if (wikiTokenizer.isWikiLink()) {
304         final String plainText = wikiTokenizer.wikiLinkText(); 
305         otherText.append("").append(plainText);
306         otherIndexBuilder.addEntryWithString(indexedEntry, plainText, EntryTypeName.WIKTIONARY_TRANSLATION_WIKI_TEXT);
307         
308       } else if (wikiTokenizer.isFunction()) {
309         final String functionName = wikiTokenizer.functionName();
310         final List<String> args = wikiTokenizer.functionPositionArgs();
311         final Map<String,String> namedArgs = wikiTokenizer.functionNamedArgs();
312         
313         if (functionName.equals("t") || functionName.equals("t+") || functionName.equals("t-") || functionName.equals("tø") || functionName.equals("apdx-t")) {
314           if (args.size() < 2) {
315             LOG.warning("{{t}} with too few args: " + line + ", title=" + title);
316             continue;
317           }
318           final String langCode = get(args, 0);
319           //if (this.langCodePattern.matcher(langCode).matches()) {
320             final String word = get(args, 1);
321             final String gender = get(args, 2);
322             final String transliteration = namedArgs.get("tr");
323             if (otherText.length() > 0) {
324               otherText.append("");
325             }
326             otherText.append(word);
327             otherIndexBuilder.addEntryWithString(indexedEntry, word, EntryTypeName.WIKTIONARY_TITLE_SINGLE, EntryTypeName.WIKTIONARY_TITLE_MULTI);
328             if (gender != null) {
329               otherText.append(String.format(" {%s}", gender));
330             }
331             if (transliteration != null) {
332               otherText.append(String.format(TRANSLITERATION_FORMAT, transliteration));
333               otherIndexBuilder.addEntryWithString(indexedEntry, transliteration, EntryTypeName.WIKTIONARY_TRANSLITERATION);
334             }
335           //}
336         } else if (functionName.equals("qualifier")) {
337           if (args.size() == 0) {
338            otherText.append(wikiTokenizer.token()); 
339           } else { 
340             String qualifier = args.get(0);
341             if (!namedArgs.isEmpty() || args.size() > 1) {
342               LOG.warning("weird qualifier: " + line);
343             }
344             // Unindexed!
345             otherText.append("(").append(qualifier).append(")");
346           }
347         } else if (encodings.contains(functionName)) {
348           otherText.append("").append(args.get(0));
349           otherIndexBuilder.addEntryWithString(indexedEntry, args.get(0), EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
350         } else if (isGender(functionName)) {
351           appendGender(otherText, functionName, args);
352         } else if (functionName.equals("g")) {
353           otherText.append("{g}");
354         } else if (functionName.equals("l")) {
355           // encodes text in various langs.
356           // lang is arg 0.
357           otherText.append("").append(args.get(1));
358           otherIndexBuilder.addEntryWithString(indexedEntry, args.get(1), EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
359           // TODO: transliteration
360         } else if (functionName.equals("term")) {
361           // cross-reference to another dictionary
362           otherText.append("").append(args.get(0));
363           otherIndexBuilder.addEntryWithString(indexedEntry, args.get(0), EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
364           // TODO: transliteration
365         } else if (functionName.equals("italbrac") || functionName.equals("gloss")) {
366           // TODO: put this text aside to use it.
367           otherText.append("[").append(args.get(0)).append("]");
368           otherIndexBuilder.addEntryWithString(indexedEntry, args.get(0), EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
369         } else if (functionName.equals("ttbc")) {
370           LOG.warning("Unexpected {{ttbc}}");
371         } else if (functionName.equals("trreq")) {
372         } else if (functionName.equals("not used")) {
373           otherText.append("(not used)");
374         } else if (functionName.equals("t-image")) {
375           // American sign language
376         } else {
377           // Unindexed!
378           namedArgs.keySet().removeAll(USELESS_WIKI_ARGS);
379           WikiTokenizer.appendFunction(otherText.append("{{"), functionName, args, namedArgs).append("}}");
380         }
381         
382       } else if (wikiTokenizer.isNewline()) {
383         assert false;
384       } else if (wikiTokenizer.isComment()) {
385       } else if (wikiTokenizer.isMarkup()) {
386       } else {
387         LOG.warning("Bad translation token: " + wikiTokenizer.token());
388       }
389     }
390     if (otherText.length() == 0) {
391       LOG.warning("Empty otherText: " + line);
392       return;
393     }
394     
395     if (lang != null) {
396       otherText.insert(0, String.format("(%s) ", lang));
397     }
398     
399     StringBuilder englishText = new StringBuilder();
400     
401     englishText.append(title);
402     if (sense != null) {
403       englishText.append(" (").append(sense).append(")");
404       enIndexBuilder.addEntryWithString(indexedEntry, sense, EntryTypeName.WIKTIONARY_TRANSLATION_SENSE, EntryTypeName.WIKTIONARY_TRANSLATION_SENSE);
405     }
406     if (pos != null) {
407       englishText.append(" (").append(pos.toLowerCase()).append(")");
408     }
409     enIndexBuilder.addEntryWithString(indexedEntry, title, EntryTypeName.WIKTIONARY_TITLE_SINGLE, EntryTypeName.WIKTIONARY_TITLE_MULTI);
410     
411     final Pair pair = new Pair(trim(englishText.toString()), trim(otherText.toString()), swap);
412     pairEntry.pairs.add(pair);
413     if (!pairsAdded.add(pair.toString())) {
414       LOG.warning("Duplicate pair: " + pair.toString());
415     }
416     if (pair.toString().equals("libero {m} :: free (adjective)")) {
417       System.out.println();
418     }
419
420   }
421
422
423   private void appendGender(final StringBuilder otherText,
424       final String functionName, final List<String> args) {
425     otherText.append("{");
426     otherText.append(functionName);
427     for (int i = 0; i < args.size(); ++i) {
428       otherText.append("|").append(args.get(i));
429     }
430     otherText.append("}");
431   }
432
433
434   private boolean isGender(final String functionName) {
435     return functionName.equals("m") || functionName.equals("f") || functionName.equals("n") || functionName.equals("p");
436   }
437   
438   Set<String> pairsAdded = new LinkedHashSet<String>();
439   
440   // -------------------------------------------------------------------------
441   
442   private void doForeignWord(final String lang, final String title, final String text) {
443     final WikiTokenizer wikiTokenizer = new WikiTokenizer(text);
444     while (wikiTokenizer.nextToken() != null) {
445       if (wikiTokenizer.isHeading()) {
446         final String headingName = wikiTokenizer.headingWikiText();
447         if (headingName.equals("Translations")) {
448           LOG.warning("Translations not in English section: " + title);
449         } else if (headingName.equals("Pronunciation")) {
450           //doPronunciation(wikiLineReader);
451         } else if (partOfSpeechHeader.matcher(headingName).matches()) {
452           doForeignPartOfSpeech(lang, title, headingName, wikiTokenizer.headingDepth(), wikiTokenizer);
453         }
454       } else {
455       }
456     }
457   }
458   
459   static final class ListSection {
460     final String firstPrefix;
461     final String firstLine;
462     final List<String> nextPrefixes = new ArrayList<String>();
463     final List<String> nextLines = new ArrayList<String>();
464     
465     public ListSection(String firstPrefix, String firstLine) {
466       this.firstPrefix = firstPrefix;
467       this.firstLine = firstLine;
468     }
469
470     @Override
471     public String toString() {
472       return firstPrefix + firstLine + "{ " + nextPrefixes + "}";
473     }
474   }
475
476
477   int foreignCount = 0;
478   private void doForeignPartOfSpeech(final String lang, String title, final String posHeading, final int posDepth, WikiTokenizer wikiTokenizer) {
479     if (++foreignCount % 1000 == 0) {
480       LOG.info("***" + lang + ", " + title + ", pos=" + posHeading + ", foreignCount=" + foreignCount);
481     }
482     if (title.equals("moro")) {
483       System.out.println();
484     }
485     
486     boolean titleAppended = false;
487     final StringBuilder foreignBuilder = new StringBuilder();
488     final Collection<String> wordForms = new ArrayList<String>();
489     final List<ListSection> listSections = new ArrayList<ListSection>();
490     
491     try {
492     
493     ListSection lastListSection = null;
494     
495     int currentHeadingDepth = posDepth;
496     while (wikiTokenizer.nextToken() != null) {
497       if (wikiTokenizer.isHeading()) {
498         currentHeadingDepth = wikiTokenizer.headingDepth();
499         
500         if (currentHeadingDepth <= posDepth) {
501           wikiTokenizer.returnToLineStart();
502           return;
503         }
504       }
505       
506       if (currentHeadingDepth > posDepth) {
507         // TODO: deal with other neat info sections
508         continue;
509       }
510       
511       if (wikiTokenizer.isFunction()) {
512         final String name = wikiTokenizer.functionName();
513         final List<String> args = wikiTokenizer.functionPositionArgs();
514         final Map<String,String> namedArgs = wikiTokenizer.functionNamedArgs();
515         // First line is generally a repeat of the title with some extra information.
516         // We need to build up the left side (foreign text, tokens) separately from the
517         // right side (English).  The left-side may get paired with multiple right sides.
518         // The left side should get filed under every form of the word in question (singular, plural).
519         
520         // For verbs, the conjugation comes later on in a deeper section.
521         // Ideally, we'd want to file every English entry with the verb
522         // under every verb form coming from the conjugation.
523         // Ie. under "fa": see: "make :: fare" and "do :: fare"
524         // But then where should we put the conjugation table?
525         // 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!)
526         // for the conjugation table from "fa".
527         // Would like to be able to link to a lang#token.
528         if (isGender(name)) {
529           appendGender(foreignBuilder, name, args);
530         } else if (name.equals("wikipedia")) {
531           namedArgs.remove("lang");
532           if (args.size() > 1 || !namedArgs.isEmpty()) {
533             // Unindexed!
534             foreignBuilder.append(wikiTokenizer.token());
535           } else if (args.size() == 1) {
536             foreignBuilder.append(wikiTokenizer.token());
537           } else {
538             //foreignBuilder.append(title);
539           }
540         } else if (name.equals("attention") || name.equals("zh-attention")) {
541           // See: http://en.wiktionary.org/wiki/Template:attention
542           // Ignore these.
543         } else if (name.equals("infl")) {
544           // See: http://en.wiktionary.org/wiki/Template:infl
545           final String langCode = get(args, 0);
546           String head = namedArgs.remove("head");
547           if (head == null) {
548             head = namedArgs.remove("title"); // Bug
549           }
550           if (head == null) {
551             head = title;
552           } else {
553             head = WikiTokenizer.toPlainText(head);
554           }
555           titleAppended = true;
556           
557           namedArgs.keySet().removeAll(USELESS_WIKI_ARGS);
558   
559           final String tr = namedArgs.remove("tr");
560           String g = namedArgs.remove("g");
561           if (g == null) {
562             g = namedArgs.remove("gender");
563           }
564           final String g2 = namedArgs.remove("g2");
565           final String g3 = namedArgs.remove("g3");
566   
567           foreignBuilder.append(head);
568     
569           if (g != null) {
570             foreignBuilder.append(" {").append(g);
571             if (g2 != null) {
572               foreignBuilder.append("|").append(g2);
573             }
574             if (g3 != null) {
575               foreignBuilder.append("|").append(g3);
576             }
577             foreignBuilder.append("}");
578           }
579     
580           if (tr != null) {
581             foreignBuilder.append(String.format(TRANSLITERATION_FORMAT, tr));
582             wordForms.add(tr);
583           }
584     
585           final String pos = get(args, 1);
586           if (pos != null) {
587             foreignBuilder.append(" (").append(pos).append(")");
588           }
589           for (int i = 2; i < args.size(); i += 2) {
590             final String inflName = get(args, i);
591             final String inflValue = get(args, i + 1);
592             foreignBuilder.append(", ").append(WikiTokenizer.toPlainText(inflName));
593             if (inflValue != null && inflValue.length() > 0) {
594               foreignBuilder.append(": ").append(WikiTokenizer.toPlainText(inflValue));
595               wordForms.add(inflValue);
596             }
597           }
598           for (final String key : namedArgs.keySet()) {
599             final String value = WikiTokenizer.toPlainText(namedArgs.get(key));
600             foreignBuilder.append(" ").append(key).append("=").append(value);
601             wordForms.add(value);
602           }
603         } else if (name.equals("it-noun")) {
604           titleAppended = true;
605           final String base = get(args, 0);
606           final String gender = get(args, 1);
607           final String singular = base + get(args, 2);
608           final String plural = base + get(args, 3);
609           foreignBuilder.append(String.format(" %s {%s}, %s {pl}", singular, gender, plural, plural));
610           wordForms.add(singular);
611           wordForms.add(plural);
612           if (!namedArgs.isEmpty() || args.size() > 4) {
613             LOG.warning("Invalid it-noun: " + wikiTokenizer.token());
614           }
615         } else if (name.equals("it-proper noun")) {
616           foreignBuilder.append(wikiTokenizer.token());
617         } else if (name.equals("it-adj")) {
618           foreignBuilder.append(wikiTokenizer.token());
619         } else if (name.startsWith("it-conj")) {
620           if (name.equals("it-conj-are")) {
621             itConjAre(args, namedArgs);
622           } else if (name.equals("it-conj-ere")) {
623           } else if (name.equals("it-conj-ire")) {
624           } else {
625             LOG.warning("Unknown conjugation: " + wikiTokenizer.token());
626           }
627         } else {
628           // Unindexed!
629           foreignBuilder.append(wikiTokenizer.token());
630           // LOG.warning("Unknown function: " + wikiTokenizer.token());
631         }
632       } else if (wikiTokenizer.isListItem()) {
633         final String prefix = wikiTokenizer.listItemPrefix();
634         if (lastListSection != null && 
635             prefix.startsWith(lastListSection.firstPrefix) && 
636             prefix.length() > lastListSection.firstPrefix.length()) {
637           lastListSection.nextPrefixes.add(prefix);
638           lastListSection.nextLines.add(wikiTokenizer.listItemWikiText());
639         } else {
640           lastListSection = new ListSection(prefix, wikiTokenizer.listItemWikiText());
641           listSections.add(lastListSection);
642         }
643       } else if (lastListSection != null) {
644         // Don't append anything after the lists, because there's crap.
645       } else if (wikiTokenizer.isWikiLink()) {
646         // Unindexed!
647         foreignBuilder.append(wikiTokenizer.wikiLinkText());
648         
649       } else if (wikiTokenizer.isPlainText()) {
650         // Unindexed!
651         foreignBuilder.append(wikiTokenizer.token());
652         
653       } else if (wikiTokenizer.isMarkup() || wikiTokenizer.isNewline() || wikiTokenizer.isComment()) {
654         // Do nothing.
655       } else {
656         LOG.warning("Unexpected token: " + wikiTokenizer.token());
657       }
658     }
659     
660     } finally {
661       // Here's where we exit.
662       // Should we make an entry even if there are no foreign list items?
663       String foreign = foreignBuilder.toString().trim();
664       if (!titleAppended && !foreign.toLowerCase().startsWith(title.toLowerCase())) {
665         foreign = String.format("%s %s", title, foreign);
666       }
667       if (!langPattern.matcher(lang).matches()) {
668         foreign = String.format("(%s) %s", lang, foreign);
669       }
670       for (final ListSection listSection : listSections) {
671         doForeignListItem(foreign, title, wordForms, listSection);
672       }
673     }
674   }
675   
676   
677   static final Pattern UNINDEXED_WIKI_TEXT = Pattern.compile(
678       "(first|second|third)-person (singular|plural)|" +
679       "present tense|" +
680       "imperative"
681       );
682
683   // Might only want to remove "lang" if it's equal to "zh", for example.
684   static final Set<String> USELESS_WIKI_ARGS = new LinkedHashSet<String>(Arrays.asList("lang", "sc", "sort", "cat"));
685
686   private void doForeignListItem(final String foreignText, String title, final Collection<String> forms, final ListSection listSection) {
687     
688     final String prefix = listSection.firstPrefix;
689     if (prefix.length() > 1) {
690       // Could just get looser and say that any prefix longer than first is a sublist.
691       LOG.warning("Prefix too long: " + listSection);
692       return;
693     }
694     
695     final PairEntry pairEntry = new PairEntry();
696     final IndexedEntry indexedEntry = new IndexedEntry(pairEntry);
697     
698     final StringBuilder englishBuilder = new StringBuilder();
699
700     final String mainLine = listSection.firstLine;
701     final WikiTokenizer englishTokenizer = new WikiTokenizer(mainLine, false);
702     while (englishTokenizer.nextToken() != null) {
703       // TODO handle form of....
704       if (englishTokenizer.isPlainText()) {
705         englishBuilder.append(englishTokenizer.token());
706         enIndexBuilder.addEntryWithString(indexedEntry, englishTokenizer.token(), EntryTypeName.WIKTIONARY_ENGLISH_DEF);
707       } else if (englishTokenizer.isWikiLink()) {
708         final String text = englishTokenizer.wikiLinkText();
709         final String link = englishTokenizer.wikiLinkDest();
710         if (link != null) {
711           if (link.contains("#English")) {
712             englishBuilder.append(text);
713             enIndexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_ENGLISH_DEF_WIKI_LINK);
714           } else if (link.contains("#") && this.langPattern.matcher(link).find()) {
715             englishBuilder.append(text);
716             otherIndexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_ENGLISH_DEF_OTHER_LANG);
717           } else if (link.equals("plural")) {
718             englishBuilder.append(text);
719           } else {
720             //LOG.warning("Special link: " + englishTokenizer.token());
721             enIndexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_ENGLISH_DEF_WIKI_LINK);
722             englishBuilder.append(text);
723           }
724         } else {
725           // link == null
726           englishBuilder.append(text);
727           if (!UNINDEXED_WIKI_TEXT.matcher(text).find()) {
728             enIndexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_ENGLISH_DEF_WIKI_LINK);
729           }
730         }
731       } else if (englishTokenizer.isFunction()) {
732         final String name = englishTokenizer.functionName();
733         final List<String> args = englishTokenizer.functionPositionArgs();
734         final Map<String,String> namedArgs = englishTokenizer.functionNamedArgs();
735         
736         if (
737             name.equals("form of") || 
738             name.contains("conjugation of") || 
739             name.contains("participle of") || 
740             name.contains("gerund of") || 
741             name.contains("feminine of") || 
742             name.contains("plural of")) {
743           String formName = name;
744           if (name.equals("form of")) {
745             formName = args.remove(0);
746           }
747           String baseForm = get(args, 1, "");
748           if ("".equals(baseForm)) {
749             baseForm = get(args, 0, null);
750             remove(args, 1, "");
751           } else {
752             remove(args, 0, null);
753           }
754           namedArgs.keySet().removeAll(USELESS_WIKI_ARGS);
755           WikiTokenizer.appendFunction(englishBuilder.append("{"), formName, args, namedArgs).append("}");
756           otherIndexBuilder.addEntryWithString(indexedEntry, baseForm, EntryTypeName.WIKTIONARY_BASE_FORM_SINGLE, EntryTypeName.WIKTIONARY_BASE_FORM_MULTI);
757           
758         } else {
759           namedArgs.keySet().removeAll(USELESS_WIKI_ARGS);
760           WikiTokenizer.appendFunction(englishBuilder.append("{{"), name, args, namedArgs).append("}}");
761 //          LOG.warning("Unexpected function: " + englishTokenizer.token());
762         }
763       } else {
764         if (englishTokenizer.isComment() || englishTokenizer.isMarkup()) {
765         } else {
766           LOG.warning("Unexpected definition type: " + englishTokenizer.token());
767         }
768       }
769     }
770         
771     final String english = trim(englishBuilder.toString());
772     if (english.length() > 0) {
773       final Pair pair = new Pair(english, trim(foreignText), this.swap);
774       pairEntry.pairs.add(pair);
775       otherIndexBuilder.addEntryWithString(indexedEntry, title, EntryTypeName.WIKTIONARY_TITLE_SINGLE, EntryTypeName.WIKTIONARY_TITLE_MULTI);
776       for (final String form : forms) {
777         otherIndexBuilder.addEntryWithString(indexedEntry, form, EntryTypeName.WIKTIONARY_INFLECTD_FORM_SINGLE, EntryTypeName.WIKTIONARY_INFLECTED_FORM_MULTI);
778       }
779     }
780     
781     // Do examples.
782     String lastForeign = null;
783     for (int i = 0; i < listSection.nextPrefixes.size(); ++i) {
784       final String nextPrefix = listSection.nextPrefixes.get(i);
785       final String nextLine = listSection.nextLines.get(i);
786       int dash = nextLine.indexOf("&mdash;");
787       int mdashLen = 7;
788       if (dash == -1) {
789         dash = nextLine.indexOf("—");
790         mdashLen = 1;
791       }
792       if (dash == -1) {
793         dash = nextLine.indexOf(" - ");
794         mdashLen = 3;
795       }
796       
797       if ((nextPrefix.equals("#:") || nextPrefix.equals("##:")) && dash != -1) {
798         final String foreignEx = nextLine.substring(0, dash);
799         final String englishEx = nextLine.substring(dash + mdashLen);
800         final Pair pair = new Pair(formatAndIndexExampleString(englishEx, enIndexBuilder, indexedEntry), formatAndIndexExampleString(foreignEx, otherIndexBuilder, indexedEntry), swap);
801         if (pair.lang1 != "--" && pair.lang1 != "--") {
802           pairEntry.pairs.add(pair);
803         }
804         lastForeign = null;
805       } else if (nextPrefix.equals("#:") || nextPrefix.equals("##:")){
806         final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
807         lastForeign = nextLine;
808         if (pair.lang1 != "--" && pair.lang1 != "--") {
809           pairEntry.pairs.add(pair);
810         }
811       } else if (nextPrefix.equals("#::") || nextPrefix.equals("#**")) {
812         if (lastForeign != null && pairEntry.pairs.size() > 0) {
813           pairEntry.pairs.remove(pairEntry.pairs.size() - 1);
814           final Pair pair = new Pair(formatAndIndexExampleString(nextLine, enIndexBuilder, indexedEntry), formatAndIndexExampleString(lastForeign, otherIndexBuilder, indexedEntry), swap);
815           if (pair.lang1 != "--" || pair.lang2 != "--") {
816             pairEntry.pairs.add(pair);
817           }
818           lastForeign = null;
819         } else {
820           LOG.warning("TODO: English example with no foreign: " + title + ", " + nextLine);
821           final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
822           if (pair.lang1 != "--" || pair.lang2 != "--") {
823             pairEntry.pairs.add(pair);
824           }
825         }
826       } else if (nextPrefix.equals("#*")) {
827         // Can't really index these.
828         final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
829         lastForeign = nextLine;
830         if (pair.lang1 != "--" || pair.lang2 != "--") {
831           pairEntry.pairs.add(pair);
832         }
833       } else if (nextPrefix.equals("#::*") || nextPrefix.equals("##") || nextPrefix.equals("#*:") || nextPrefix.equals("#:*") || true) {
834         final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
835         if (pair.lang1 != "--" || pair.lang2 != "--") {
836           pairEntry.pairs.add(pair);
837         }
838 //      } else {
839 //        assert false;
840       }
841     }
842   }
843   
844   private String formatAndIndexExampleString(final String example, final IndexBuilder indexBuilder, final IndexedEntry indexedEntry) {
845     final WikiTokenizer wikiTokenizer = new WikiTokenizer(example, false);
846     final StringBuilder builder = new StringBuilder();
847     boolean insideTripleQuotes = false;
848     while (wikiTokenizer.nextToken() != null) {
849       if (wikiTokenizer.isPlainText()) {
850         builder.append(wikiTokenizer.token());
851         if (indexBuilder != null) {
852           indexBuilder.addEntryWithString(indexedEntry, wikiTokenizer.token(), EntryTypeName.WIKTIONARY_EXAMPLE);
853         }
854       } else if (wikiTokenizer.isWikiLink()) {
855         final String text = wikiTokenizer.wikiLinkText().replaceAll("'", ""); 
856         builder.append(text);
857         if (indexBuilder != null) {
858           indexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_EXAMPLE);
859         }
860       } else if (wikiTokenizer.isFunction()) {
861         builder.append(wikiTokenizer.token());
862       } else if (wikiTokenizer.isMarkup()) {
863         if (wikiTokenizer.token().equals("'''")) {
864           insideTripleQuotes = !insideTripleQuotes;
865         }
866       } else if (wikiTokenizer.isComment() || wikiTokenizer.isNewline()) {
867         // Do nothing.
868       } else {
869         LOG.warning("unexpected token: " + wikiTokenizer.token());
870       }
871     }
872     final String result = trim(builder.toString());
873     return result.length() > 0 ? result : "--";
874   }
875
876
877   private void itConjAre(List<String> args, Map<String, String> namedArgs) {
878     final String base = args.get(0);
879     final String aux = args.get(1);
880     
881     putIfMissing(namedArgs, "inf", base + "are");
882     putIfMissing(namedArgs, "aux", aux);
883     putIfMissing(namedArgs, "ger", base + "ando");
884     putIfMissing(namedArgs, "presp", base + "ante");
885     putIfMissing(namedArgs, "pastp", base + "ato");
886     // Present
887     putIfMissing(namedArgs, "pres1s", base + "o");
888     putIfMissing(namedArgs, "pres2s", base + "i");
889     putIfMissing(namedArgs, "pres3s", base + "a");
890     putIfMissing(namedArgs, "pres1p", base + "iamo");
891     putIfMissing(namedArgs, "pres2p", base + "ate");
892     putIfMissing(namedArgs, "pres3p", base + "ano");
893     // Imperfect
894     putIfMissing(namedArgs, "imperf1s", base + "avo");
895     putIfMissing(namedArgs, "imperf2s", base + "avi");
896     putIfMissing(namedArgs, "imperf3s", base + "ava");
897     putIfMissing(namedArgs, "imperf1p", base + "avamo");
898     putIfMissing(namedArgs, "imperf2p", base + "avate");
899     putIfMissing(namedArgs, "imperf3p", base + "avano");
900     // Passato remoto
901     putIfMissing(namedArgs, "prem1s", base + "ai");
902     putIfMissing(namedArgs, "prem2s", base + "asti");
903     putIfMissing(namedArgs, "prem3s", base + "ò");
904     putIfMissing(namedArgs, "prem1p", base + "ammo");
905     putIfMissing(namedArgs, "prem2p", base + "aste");
906     putIfMissing(namedArgs, "prem3p", base + "arono");
907     // Future
908     putIfMissing(namedArgs, "fut1s", base + "erò");
909     putIfMissing(namedArgs, "fut2s", base + "erai");
910     putIfMissing(namedArgs, "fut3s", base + "erà");
911     putIfMissing(namedArgs, "fut1p", base + "eremo");
912     putIfMissing(namedArgs, "fut2p", base + "erete");
913     putIfMissing(namedArgs, "fut3p", base + "eranno");
914     // Conditional
915     putIfMissing(namedArgs, "cond1s", base + "erei");
916     putIfMissing(namedArgs, "cond2s", base + "eresti");
917     putIfMissing(namedArgs, "cond3s", base + "erebbe");
918     putIfMissing(namedArgs, "cond1p", base + "eremmo");
919     putIfMissing(namedArgs, "cond2p", base + "ereste");
920     putIfMissing(namedArgs, "cond3p", base + "erebbero");
921     // Subjunctive / congiuntivo
922     putIfMissing(namedArgs, "sub123s", base + "i");
923     putIfMissing(namedArgs, "sub1p", base + "iamo");
924     putIfMissing(namedArgs, "sub2p", base + "iate");
925     putIfMissing(namedArgs, "sub3p", base + "ino");
926     // Imperfect subjunctive
927     putIfMissing(namedArgs, "impsub12s", base + "assi");
928     putIfMissing(namedArgs, "impsub3s", base + "asse");
929     putIfMissing(namedArgs, "impsub1p", base + "assimo");
930     putIfMissing(namedArgs, "impsub2p", base + "aste");
931     putIfMissing(namedArgs, "impsub3p", base + "assero");
932     // Imperative
933     putIfMissing(namedArgs, "imp2s", base + "a");
934     putIfMissing(namedArgs, "imp3s", base + "i");
935     putIfMissing(namedArgs, "imp1p", base + "iamo");
936     putIfMissing(namedArgs, "imp2p", base + "ate");
937     putIfMissing(namedArgs, "imp3p", base + "ino");
938
939
940     itConj(args, namedArgs);
941   }
942
943
944   private void itConj(List<String> args, Map<String, String> namedArgs) {
945     // TODO Auto-generated method stub
946     
947   }
948
949
950   private static void putIfMissing(final Map<String, String> namedArgs, final String key,
951       final String value) {
952     final String oldValue = namedArgs.get(key);
953     if (oldValue == null || oldValue.length() == 0) {
954       namedArgs.put(key, value);
955     }
956   }
957   
958   // TODO: check how ='' and =| are manifested....
959   // TODO: get this right in -are
960   private static void putOrNullify(final Map<String, String> namedArgs, final String key,
961       final String value) {
962     final String oldValue = namedArgs.get(key);
963     if (oldValue == null/* || oldValue.length() == 0*/) {
964       namedArgs.put(key, value);
965     } else {
966       if (oldValue.equals("''")) {
967         namedArgs.put(key, "");
968       }
969     }
970   }
971
972   static final Pattern whitespace = Pattern.compile("\\s+");
973   static String trim(final String s) {
974     return whitespace.matcher(s).replaceAll(" ").trim();
975   }
976
977   
978 }