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