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