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