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