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