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.replace("=", "").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());
180 } else if (wikiTokenizer.isHtml()) {
181 if (!wikiTokenizer.token().startsWith("<ref>")) {
182 foreignBuilder.append(wikiTokenizer.token());
184 } else if (wikiTokenizer.isMarkup() ||
185 wikiTokenizer.isNewline() ||
186 wikiTokenizer.isComment()) {
189 LOG.warning("Unexpected token: " + wikiTokenizer.token());
190 assert !wikiTokenizer.errors().isEmpty();
195 // Here's where we exit.
196 // Should we make an entry even if there are no foreign list items?
197 String foreign = foreignBuilder.toString().trim();
198 if (!titleAppended && !foreign.toLowerCase().startsWith(title.toLowerCase())) {
199 foreign = String.format("%s %s", title, foreign);
201 if (!langPattern.matcher(lang).matches()) {
202 foreign = String.format("(%s) %s", lang, foreign);
204 for (final EnForeignParser.ListSection listSection : listSections) {
205 doForeignListSection(foreign, title, wordForms, listSection);
210 private void doForeignListSection(final String foreignText, String title, final Collection<String> forms, final EnForeignParser.ListSection listSection) {
211 state = State.ENGLISH_DEF_OF_FOREIGN;
212 final String prefix = listSection.firstPrefix;
213 if (prefix.length() > 1) {
214 // Could just get looser and say that any prefix longer than first is a sublist.
215 LOG.warning("Prefix '" + prefix + "' too long: " + listSection);
216 incrementCount("WARNING: Prefix too long");
220 final PairEntry pairEntry = new PairEntry(entrySource);
221 final IndexedEntry indexedEntry = new IndexedEntry(pairEntry);
222 indexedEntry.isValid = true;
224 entryIsFormOfSomething = false;
225 final StringBuilder englishBuilder = new StringBuilder();
226 final String mainLine = listSection.firstLine;
227 appendAndIndexWikiCallback.reset(englishBuilder, indexedEntry);
228 appendAndIndexWikiCallback.dispatch(mainLine, enIndexBuilder, EntryTypeName.WIKTIONARY_ENGLISH_DEF);
230 final String english = trim(englishBuilder.toString());
231 if (english.length() > 0) {
232 final Pair pair = new Pair(english, trim(foreignText), this.swap);
233 pairEntry.pairs.add(pair);
234 foreignIndexBuilder.addEntryWithString(indexedEntry, title, entryIsFormOfSomething ? EntryTypeName.WIKTIONARY_IS_FORM_OF_SOMETHING_ELSE : EntryTypeName.WIKTIONARY_TITLE_MULTI);
235 for (final String form : forms) {
236 foreignIndexBuilder.addEntryWithString(indexedEntry, form, EntryTypeName.WIKTIONARY_INFLECTED_FORM_MULTI);
241 String lastForeign = null;
242 for (int i = 0; i < listSection.nextPrefixes.size(); ++i) {
243 final String nextPrefix = listSection.nextPrefixes.get(i);
244 String nextLine = listSection.nextLines.get(i);
246 // TODO: This splitting is not sensitive to wiki code.
247 int dash = nextLine.indexOf("—");
250 dash = nextLine.indexOf("—");
254 dash = nextLine.indexOf(" - ");
258 if ((nextPrefix.equals("#:") || nextPrefix.equals("##:")) && dash != -1) {
259 final String foreignEx = nextLine.substring(0, dash);
260 final String englishEx = nextLine.substring(dash + mdashLen);
261 final Pair pair = new Pair(formatAndIndexExampleString(englishEx, enIndexBuilder, indexedEntry), formatAndIndexExampleString(foreignEx, foreignIndexBuilder, indexedEntry), swap);
262 if (pair.lang1 != "--" && pair.lang1 != "--") {
263 pairEntry.pairs.add(pair);
266 } else if (nextPrefix.equals("#:") || nextPrefix.equals("##:")){
267 final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
268 lastForeign = nextLine;
269 if (pair.lang1 != "--" && pair.lang1 != "--") {
270 pairEntry.pairs.add(pair);
272 } else if (nextPrefix.equals("#::") || nextPrefix.equals("#**")) {
273 if (lastForeign != null && pairEntry.pairs.size() > 0) {
274 if (i + 1 < listSection.nextPrefixes.size()) {
275 // Chinese has sometimes multiple foreign lines
276 final String nextNextPrefix = listSection.nextPrefixes.get(i + 1);
277 if (nextNextPrefix.equals("#::") || nextNextPrefix.equals("#**")) {
279 nextLine += "\n" + listSection.nextLines.get(i);
282 pairEntry.pairs.remove(pairEntry.pairs.size() - 1);
283 final Pair pair = new Pair(formatAndIndexExampleString(nextLine, enIndexBuilder, indexedEntry), formatAndIndexExampleString(lastForeign, foreignIndexBuilder, indexedEntry), swap);
284 if (pair.lang1 != "--" || pair.lang2 != "--") {
285 pairEntry.pairs.add(pair);
289 LOG.warning("TODO: English example with no foreign: " + title + ", " + nextLine);
290 final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
291 if (pair.lang1 != "--" || pair.lang2 != "--") {
292 pairEntry.pairs.add(pair);
295 } else if (nextPrefix.equals("#*")) {
296 // Can't really index these.
297 final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
298 lastForeign = nextLine;
299 if (pair.lang1 != "--" || pair.lang2 != "--") {
300 pairEntry.pairs.add(pair);
302 } else if (nextPrefix.equals("#::*") || nextPrefix.equals("##") || nextPrefix.equals("#*:") || nextPrefix.equals("#:*") || true) {
303 final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
304 if (pair.lang1 != "--" || pair.lang2 != "--") {
305 pairEntry.pairs.add(pair);
313 private String formatAndIndexExampleString(final String example, final IndexBuilder indexBuilder, final IndexedEntry indexedEntry) {
315 // if (wikiTokenizer.token().equals("'''")) {
316 // insideTripleQuotes = !insideTripleQuotes;
318 final StringBuilder builder = new StringBuilder();
319 appendAndIndexWikiCallback.reset(builder, indexedEntry);
320 appendAndIndexWikiCallback.entryTypeName = EntryTypeName.WIKTIONARY_EXAMPLE;
321 appendAndIndexWikiCallback.entryTypeNameSticks = true;
323 // TODO: this is a hack needed because we don't safely split on the dash.
324 appendAndIndexWikiCallback.dispatch(example, indexBuilder, EntryTypeName.WIKTIONARY_EXAMPLE);
325 } catch (AssertionError e) {
328 final String result = trim(builder.toString());
329 return result.length() > 0 ? result : "--";