1 // Copyright 2012 Google Inc. All Rights Reserved.
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
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
15 package com.hughes.android.dictionary.parser.wiktionary;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.List;
21 import java.util.regex.Pattern;
23 import com.hughes.android.dictionary.engine.EntryTypeName;
24 import com.hughes.android.dictionary.engine.IndexBuilder;
25 import com.hughes.android.dictionary.engine.IndexedEntry;
26 import com.hughes.android.dictionary.engine.PairEntry;
27 import com.hughes.android.dictionary.engine.PairEntry.Pair;
28 import com.hughes.android.dictionary.parser.WikiTokenizer;
30 public final class EnForeignParser extends EnParser {
32 public EnForeignParser(final IndexBuilder enIndexBuilder,
33 final IndexBuilder otherIndexBuilder, final Pattern langPattern,
34 final Pattern langCodePattern, final boolean swap) {
35 super(enIndexBuilder, otherIndexBuilder, langPattern, langCodePattern, swap);
39 void parseSection(String heading, String text) {
40 if (isIgnorableTitle(title)) {
43 final String lang = heading.replaceAll("=", "").trim();
44 if (!langPattern.matcher(lang).find()){
48 final WikiTokenizer wikiTokenizer = new WikiTokenizer(text);
49 while (wikiTokenizer.nextToken() != null) {
50 if (wikiTokenizer.isHeading()) {
51 final String headingName = wikiTokenizer.headingWikiText();
52 if (headingName.equals("Translations")) {
53 LOG.warning("Translations not in English section: " + title);
54 incrementCount("WARNING: Translations not in English section");
55 } else if (headingName.equals("Pronunciation")) {
56 //doPronunciation(wikiLineReader);
57 } else if (partOfSpeechHeader.matcher(headingName).matches()) {
58 doForeignPartOfSpeech(lang, headingName, wikiTokenizer.headingDepth(), wikiTokenizer);
61 // It's not a heading.
62 // TODO: optimization: skip to next heading.
67 static final class ListSection {
68 final String firstPrefix;
69 final String firstLine;
70 final List<String> nextPrefixes = new ArrayList<String>();
71 final List<String> nextLines = new ArrayList<String>();
73 public ListSection(String firstPrefix, String firstLine) {
74 this.firstPrefix = firstPrefix;
75 this.firstLine = firstLine;
79 public String toString() {
80 return firstPrefix + firstLine + "{ " + nextPrefixes + "}";
85 private void doForeignPartOfSpeech(final String lang, String posHeading, final int posDepth, WikiTokenizer wikiTokenizer) {
86 if (++foreignCount % 1000 == 0) {
87 LOG.info("***" + lang + ", " + title + ", pos=" + posHeading + ", foreignCount=" + foreignCount);
89 if (title.equals("6")) {
93 final StringBuilder foreignBuilder = new StringBuilder();
94 final List<EnForeignParser.ListSection> listSections = new ArrayList<EnForeignParser.ListSection>();
96 appendAndIndexWikiCallback.reset(foreignBuilder, null);
97 this.state = State.ENGLISH_DEF_OF_FOREIGN; // TODO: this is wrong, need new category....
98 titleAppended = false;
103 EnForeignParser.ListSection lastListSection = null;
105 int currentHeadingDepth = posDepth;
106 while (wikiTokenizer.nextToken() != null) {
107 if (wikiTokenizer.isHeading()) {
108 currentHeadingDepth = wikiTokenizer.headingDepth();
110 if (currentHeadingDepth <= posDepth) {
111 wikiTokenizer.returnToLineStart();
116 if (currentHeadingDepth > posDepth) {
117 // TODO: deal with other neat info sections inside POS
121 if (wikiTokenizer.isFunction()) {
122 final String name = wikiTokenizer.functionName();
123 final List<String> args = wikiTokenizer.functionPositionArgs();
124 final Map<String,String> namedArgs = wikiTokenizer.functionNamedArgs();
125 // First line is generally a repeat of the title with some extra information.
126 // We need to build up the left side (foreign text, tokens) separately from the
127 // right side (English). The left-side may get paired with multiple right sides.
128 // The left side should get filed under every form of the word in question (singular, plural).
130 // For verbs, the conjugation comes later on in a deeper section.
131 // Ideally, we'd want to file every English entry with the verb
132 // under every verb form coming from the conjugation.
133 // Ie. under "fa": see: "make :: fare" and "do :: fare"
134 // But then where should we put the conjugation table?
135 // 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!)
136 // for the conjugation table from "fa".
137 // Would like to be able to link to a lang#token.
140 String head = namedArgs.remove("head");
141 final String tr = namedArgs.remove("tr");
142 if (head == null && tr != null && !titleAppended) {
146 final String form = appendAndIndexWikiCallback.dispatch(head, EntryTypeName.WIKTIONARY_TITLE_MULTI);
148 appendAndIndexWikiCallback.builder.append(" ");
149 titleAppended = true;
152 appendAndIndexWikiCallback.builder.append(" (");
153 final String form = appendAndIndexWikiCallback.dispatch(tr, EntryTypeName.WIKTIONARY_TRANSLITERATION);
155 appendAndIndexWikiCallback.builder.append(") ");
158 appendAndIndexWikiCallback.onFunction(wikiTokenizer, name, args, namedArgs);
160 } else if (wikiTokenizer.isListItem()) {
161 final String prefix = wikiTokenizer.listItemPrefix();
162 if (lastListSection != null &&
163 prefix.startsWith(lastListSection.firstPrefix) &&
164 prefix.length() > lastListSection.firstPrefix.length()) {
165 lastListSection.nextPrefixes.add(prefix);
166 lastListSection.nextLines.add(wikiTokenizer.listItemWikiText());
168 lastListSection = new ListSection(prefix, wikiTokenizer.listItemWikiText());
169 listSections.add(lastListSection);
171 } else if (lastListSection != null) {
172 // Don't append anything after the lists, because there's crap.
173 } else if (wikiTokenizer.isWikiLink()) {
175 foreignBuilder.append(wikiTokenizer.wikiLinkText());
177 } else if (wikiTokenizer.isPlainText()) {
179 foreignBuilder.append(wikiTokenizer.token());
181 } else if (wikiTokenizer.isMarkup() || wikiTokenizer.isNewline() || wikiTokenizer.isComment()) {
184 LOG.warning("Unexpected token: " + wikiTokenizer.token());
185 assert !wikiTokenizer.errors().isEmpty();
190 // Here's where we exit.
191 // Should we make an entry even if there are no foreign list items?
192 String foreign = foreignBuilder.toString().trim();
193 if (!titleAppended && !foreign.toLowerCase().startsWith(title.toLowerCase())) {
194 foreign = String.format("%s %s", title, foreign);
196 if (!langPattern.matcher(lang).matches()) {
197 foreign = String.format("(%s) %s", lang, foreign);
199 for (final EnForeignParser.ListSection listSection : listSections) {
200 doForeignListSection(foreign, title, wordForms, listSection);
205 private void doForeignListSection(final String foreignText, String title, final Collection<String> forms, final EnForeignParser.ListSection listSection) {
206 state = State.ENGLISH_DEF_OF_FOREIGN;
207 final String prefix = listSection.firstPrefix;
208 if (prefix.length() > 1) {
209 // Could just get looser and say that any prefix longer than first is a sublist.
210 LOG.warning("Prefix too long: " + listSection);
211 incrementCount("WARNING: Prefix too long");
215 final PairEntry pairEntry = new PairEntry(entrySource);
216 final IndexedEntry indexedEntry = new IndexedEntry(pairEntry);
217 indexedEntry.isValid = true;
219 entryIsFormOfSomething = false;
220 final StringBuilder englishBuilder = new StringBuilder();
221 final String mainLine = listSection.firstLine;
222 appendAndIndexWikiCallback.reset(englishBuilder, indexedEntry);
223 appendAndIndexWikiCallback.dispatch(mainLine, enIndexBuilder, EntryTypeName.WIKTIONARY_ENGLISH_DEF);
225 final String english = trim(englishBuilder.toString());
226 if (english.length() > 0) {
227 final Pair pair = new Pair(english, trim(foreignText), this.swap);
228 pairEntry.pairs.add(pair);
229 foreignIndexBuilder.addEntryWithString(indexedEntry, title, entryIsFormOfSomething ? EntryTypeName.WIKTIONARY_IS_FORM_OF_SOMETHING_ELSE : EntryTypeName.WIKTIONARY_TITLE_MULTI);
230 for (final String form : forms) {
231 foreignIndexBuilder.addEntryWithString(indexedEntry, form, EntryTypeName.WIKTIONARY_INFLECTED_FORM_MULTI);
236 String lastForeign = null;
237 for (int i = 0; i < listSection.nextPrefixes.size(); ++i) {
238 final String nextPrefix = listSection.nextPrefixes.get(i);
239 final String nextLine = listSection.nextLines.get(i);
241 // TODO: This splitting is not sensitive to wiki code.
242 int dash = nextLine.indexOf("—");
245 dash = nextLine.indexOf("—");
249 dash = nextLine.indexOf(" - ");
253 if ((nextPrefix.equals("#:") || nextPrefix.equals("##:")) && dash != -1) {
254 final String foreignEx = nextLine.substring(0, dash);
255 final String englishEx = nextLine.substring(dash + mdashLen);
256 final Pair pair = new Pair(formatAndIndexExampleString(englishEx, enIndexBuilder, indexedEntry), formatAndIndexExampleString(foreignEx, foreignIndexBuilder, indexedEntry), swap);
257 if (pair.lang1 != "--" && pair.lang1 != "--") {
258 pairEntry.pairs.add(pair);
261 } else if (nextPrefix.equals("#:") || nextPrefix.equals("##:")){
262 final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
263 lastForeign = nextLine;
264 if (pair.lang1 != "--" && pair.lang1 != "--") {
265 pairEntry.pairs.add(pair);
267 } else if (nextPrefix.equals("#::") || nextPrefix.equals("#**")) {
268 if (lastForeign != null && pairEntry.pairs.size() > 0) {
269 pairEntry.pairs.remove(pairEntry.pairs.size() - 1);
270 final Pair pair = new Pair(formatAndIndexExampleString(nextLine, enIndexBuilder, indexedEntry), formatAndIndexExampleString(lastForeign, foreignIndexBuilder, indexedEntry), swap);
271 if (pair.lang1 != "--" || pair.lang2 != "--") {
272 pairEntry.pairs.add(pair);
276 LOG.warning("TODO: English example with no foreign: " + title + ", " + nextLine);
277 final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
278 if (pair.lang1 != "--" || pair.lang2 != "--") {
279 pairEntry.pairs.add(pair);
282 } else if (nextPrefix.equals("#*")) {
283 // Can't really index these.
284 final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
285 lastForeign = nextLine;
286 if (pair.lang1 != "--" || pair.lang2 != "--") {
287 pairEntry.pairs.add(pair);
289 } else if (nextPrefix.equals("#::*") || nextPrefix.equals("##") || nextPrefix.equals("#*:") || nextPrefix.equals("#:*") || true) {
290 final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
291 if (pair.lang1 != "--" || pair.lang2 != "--") {
292 pairEntry.pairs.add(pair);
300 private String formatAndIndexExampleString(final String example, final IndexBuilder indexBuilder, final IndexedEntry indexedEntry) {
302 // if (wikiTokenizer.token().equals("'''")) {
303 // insideTripleQuotes = !insideTripleQuotes;
305 final StringBuilder builder = new StringBuilder();
306 appendAndIndexWikiCallback.reset(builder, indexedEntry);
307 appendAndIndexWikiCallback.entryTypeName = EntryTypeName.WIKTIONARY_EXAMPLE;
308 appendAndIndexWikiCallback.entryTypeNameSticks = true;
310 // TODO: this is a hack needed because we don't safely split on the dash.
311 appendAndIndexWikiCallback.dispatch(example, indexBuilder, EntryTypeName.WIKTIONARY_EXAMPLE);
312 } catch (AssertionError e) {
315 final String result = trim(builder.toString());
316 return result.length() > 0 ? result : "--";