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