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.parser.WikiTokenizer;
29 public final class EnForeignParser extends EnParser {
31 public EnForeignParser(final IndexBuilder enIndexBuilder,
32 final IndexBuilder otherIndexBuilder, final Pattern langPattern,
33 final Pattern langCodePattern, final boolean swap) {
34 super(enIndexBuilder, otherIndexBuilder, langPattern, langCodePattern, swap);
38 void parseSection(String heading, String text) {
39 if (isIgnorableTitle(title)) {
42 final String lang = heading.replace("=", "").trim();
43 if (!langPattern.matcher(lang).find()) {
47 final WikiTokenizer wikiTokenizer = new WikiTokenizer(text);
48 while (wikiTokenizer.nextToken() != null) {
49 if (wikiTokenizer.isHeading()) {
50 final String headingName = wikiTokenizer.headingWikiText();
51 if (headingName.equals("Translations")) {
52 LOG.warning("Translations not in English section: " + title);
53 incrementCount("WARNING: Translations not in English section");
54 } else if (headingName.equals("Pronunciation")) {
55 //doPronunciation(wikiLineReader);
56 } else if (headingName.startsWith(" {{S|")) {
57 // HACK to support parsing frwiktionary
58 String[] parts = headingName.split("\\|");
59 if (parts.length > 2 && langCodePattern.matcher(parts[2]).find() &&
60 (parts.length < 4 || !parts[3].startsWith("flexion"))) {
61 doForeignPartOfSpeech(lang, headingName, wikiTokenizer.headingDepth(), wikiTokenizer);
63 } else if (partOfSpeechHeader.matcher(headingName).matches()) {
64 doForeignPartOfSpeech(lang, headingName, wikiTokenizer.headingDepth(), wikiTokenizer);
67 // It's not a heading.
68 // TODO: optimization: skip to next heading.
73 static final class ListSection {
74 final String firstPrefix;
75 final String firstLine;
76 final List<String> nextPrefixes = new ArrayList<String>();
77 final List<String> nextLines = new ArrayList<String>();
79 public ListSection(String firstPrefix, String firstLine) {
80 this.firstPrefix = firstPrefix;
81 this.firstLine = firstLine;
85 public String toString() {
86 return firstPrefix + firstLine + "{ " + nextPrefixes + "}";
91 private void doForeignPartOfSpeech(final String lang, String posHeading, final int posDepth, WikiTokenizer wikiTokenizer) {
92 if (++foreignCount % 1000 == 0) {
93 LOG.info("***" + lang + ", " + title + ", pos=" + posHeading + ", foreignCount=" + foreignCount);
95 if (title.equals("6")) {
99 final StringBuilder foreignBuilder = new StringBuilder();
100 final List<EnForeignParser.ListSection> listSections = new ArrayList<EnForeignParser.ListSection>();
102 appendAndIndexWikiCallback.reset(foreignBuilder, null);
103 this.state = State.ENGLISH_DEF_OF_FOREIGN; // TODO: this is wrong, need new category....
104 titleAppended = false;
109 EnForeignParser.ListSection lastListSection = null;
111 int currentHeadingDepth = posDepth;
112 while (wikiTokenizer.nextToken() != null) {
113 if (wikiTokenizer.isHeading()) {
114 currentHeadingDepth = wikiTokenizer.headingDepth();
116 if (currentHeadingDepth <= posDepth) {
117 wikiTokenizer.returnToLineStart();
122 if (currentHeadingDepth > posDepth) {
123 // TODO: deal with other neat info sections inside POS
127 if (wikiTokenizer.isFunction()) {
128 final String name = wikiTokenizer.functionName();
129 final List<String> args = wikiTokenizer.functionPositionArgs();
130 final Map<String,String> namedArgs = wikiTokenizer.functionNamedArgs();
131 // First line is generally a repeat of the title with some extra information.
132 // We need to build up the left side (foreign text, tokens) separately from the
133 // right side (English). The left-side may get paired with multiple right sides.
134 // The left side should get filed under every form of the word in question (singular, plural).
136 // For verbs, the conjugation comes later on in a deeper section.
137 // Ideally, we'd want to file every English entry with the verb
138 // under every verb form coming from the conjugation.
139 // Ie. under "fa": see: "make :: fare" and "do :: fare"
140 // But then where should we put the conjugation table?
141 // 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!)
142 // for the conjugation table from "fa".
143 // Would like to be able to link to a lang#token.
146 String head = namedArgs.remove("head");
147 final String tr = namedArgs.remove("tr");
148 if (head == null && tr != null && !titleAppended) {
152 final String form = appendAndIndexWikiCallback.dispatch(head, EntryTypeName.WIKTIONARY_TITLE_MULTI);
154 appendAndIndexWikiCallback.builder.append(" ");
155 titleAppended = true;
158 appendAndIndexWikiCallback.builder.append(" (");
159 final String form = appendAndIndexWikiCallback.dispatch(tr, EntryTypeName.WIKTIONARY_TRANSLITERATION);
161 appendAndIndexWikiCallback.builder.append(") ");
164 appendAndIndexWikiCallback.onFunction(wikiTokenizer, name, args, namedArgs);
166 } else if (wikiTokenizer.isListItem()) {
167 final String prefix = wikiTokenizer.listItemPrefix();
168 if (lastListSection != null &&
169 prefix.startsWith(lastListSection.firstPrefix) &&
170 prefix.length() > lastListSection.firstPrefix.length()) {
171 lastListSection.nextPrefixes.add(prefix);
172 lastListSection.nextLines.add(wikiTokenizer.listItemWikiText());
174 lastListSection = new ListSection(prefix, wikiTokenizer.listItemWikiText());
175 listSections.add(lastListSection);
177 } else if (lastListSection != null) {
178 // Don't append anything after the lists, because there's crap.
179 } else if (wikiTokenizer.isWikiLink()) {
181 foreignBuilder.append(wikiTokenizer.wikiLinkText());
183 } else if (wikiTokenizer.isPlainText()) {
185 foreignBuilder.append(wikiTokenizer.token());
186 } else if (wikiTokenizer.isHtml()) {
187 if (!wikiTokenizer.token().startsWith("<ref>")) {
188 foreignBuilder.append(wikiTokenizer.token());
190 } else if (wikiTokenizer.isMarkup() ||
191 wikiTokenizer.isNewline() ||
192 wikiTokenizer.isComment()) {
195 LOG.warning("Unexpected token: " + wikiTokenizer.token());
196 assert !wikiTokenizer.errors().isEmpty();
201 // Here's where we exit.
202 // Should we make an entry even if there are no foreign list items?
203 String foreign = foreignBuilder.toString().trim();
204 if (!titleAppended && !foreign.toLowerCase().startsWith(title.toLowerCase())) {
205 foreign = String.format("%s %s", title, foreign);
207 if (!langPattern.matcher(lang).matches()) {
208 foreign = String.format("(%s) %s", lang, foreign);
210 for (final EnForeignParser.ListSection listSection : listSections) {
211 doForeignListSection(foreign, title, wordForms, listSection);
216 private void doForeignListSection(final String foreignText, String title, final Collection<String> forms, final EnForeignParser.ListSection listSection) {
217 state = State.ENGLISH_DEF_OF_FOREIGN;
218 final String prefix = listSection.firstPrefix;
219 if (prefix.length() > 1) {
220 // Could just get looser and say that any prefix longer than first is a sublist.
221 LOG.warning("Prefix '" + prefix + "' too long: " + listSection);
222 incrementCount("WARNING: Prefix too long");
226 final PairEntry pairEntry = new PairEntry(entrySource);
227 final IndexedEntry indexedEntry = new IndexedEntry(pairEntry);
228 indexedEntry.isValid = true;
230 entryIsFormOfSomething = false;
231 final StringBuilder englishBuilder = new StringBuilder();
232 final String mainLine = listSection.firstLine;
233 appendAndIndexWikiCallback.reset(englishBuilder, indexedEntry);
234 appendAndIndexWikiCallback.dispatch(mainLine, enIndexBuilder, EntryTypeName.WIKTIONARY_ENGLISH_DEF);
236 final String english = trim(englishBuilder.toString());
237 if (english.length() > 0) {
238 final PairEntry.Pair pair = new PairEntry.Pair(english, trim(foreignText), this.swap);
239 pairEntry.pairs.add(pair);
240 foreignIndexBuilder.addEntryWithString(indexedEntry, title, entryIsFormOfSomething ? EntryTypeName.WIKTIONARY_IS_FORM_OF_SOMETHING_ELSE : EntryTypeName.WIKTIONARY_TITLE_MULTI);
241 for (final String form : forms) {
242 foreignIndexBuilder.addEntryWithString(indexedEntry, form, EntryTypeName.WIKTIONARY_INFLECTED_FORM_MULTI);
247 String lastForeign = null;
248 for (int i = 0; i < listSection.nextPrefixes.size(); ++i) {
249 final String nextPrefix = listSection.nextPrefixes.get(i);
250 String nextLine = listSection.nextLines.get(i);
252 // TODO: This splitting is not sensitive to wiki code.
253 int dash = nextLine.indexOf("—");
256 dash = nextLine.indexOf("—");
260 dash = nextLine.indexOf(" - ");
264 if ((nextPrefix.equals("#:") || nextPrefix.equals("##:")) && dash != -1) {
265 final String foreignEx = nextLine.substring(0, dash);
266 final String englishEx = nextLine.substring(dash + mdashLen);
267 final PairEntry.Pair pair = new PairEntry.Pair(formatAndIndexExampleString(englishEx, enIndexBuilder, indexedEntry), formatAndIndexExampleString(foreignEx, foreignIndexBuilder, indexedEntry), swap);
268 if (pair.lang1 != "--" && pair.lang1 != "--") {
269 pairEntry.pairs.add(pair);
272 // TODO: make #* and #*: work
273 } else if (nextPrefix.equals("#:") || nextPrefix.equals("##:")/* || nextPrefix.equals("#*")*/) {
274 final PairEntry.Pair pair = new PairEntry.Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
275 lastForeign = nextLine;
276 if (pair.lang1 != "--" && pair.lang1 != "--") {
277 pairEntry.pairs.add(pair);
279 } else if (nextPrefix.equals("#::") || nextPrefix.equals("#**")/* || nextPrefix.equals("#*:")*/) {
280 if (lastForeign != null && pairEntry.pairs.size() > 0) {
281 if (i + 1 < listSection.nextPrefixes.size()) {
282 // Chinese has sometimes multiple foreign lines
283 final String nextNextPrefix = listSection.nextPrefixes.get(i + 1);
284 if (nextNextPrefix.equals("#::") || nextNextPrefix.equals("#**")) {
286 nextLine += "\n" + listSection.nextLines.get(i);
289 pairEntry.pairs.remove(pairEntry.pairs.size() - 1);
290 final PairEntry.Pair pair = new PairEntry.Pair(formatAndIndexExampleString(nextLine, enIndexBuilder, indexedEntry), formatAndIndexExampleString(lastForeign, foreignIndexBuilder, indexedEntry), swap);
291 if (pair.lang1 != "--" || pair.lang2 != "--") {
292 pairEntry.pairs.add(pair);
296 LOG.warning("TODO: English example with no foreign: " + title + ", " + nextLine);
297 final PairEntry.Pair pair = new PairEntry.Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
298 if (pair.lang1 != "--" || pair.lang2 != "--") {
299 pairEntry.pairs.add(pair);
302 } else if (nextPrefix.equals("#*")) {
303 // Can't really index these.
304 final PairEntry.Pair pair = new PairEntry.Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
305 lastForeign = nextLine;
306 if (pair.lang1 != "--" || pair.lang2 != "--") {
307 pairEntry.pairs.add(pair);
309 } else if (nextPrefix.equals("#::*") || nextPrefix.equals("##") || nextPrefix.equals("#*:") || nextPrefix.equals("#:*") || true) {
310 final PairEntry.Pair pair = new PairEntry.Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
311 if (pair.lang1 != "--" || pair.lang2 != "--") {
312 pairEntry.pairs.add(pair);
320 private String formatAndIndexExampleString(final String example, final IndexBuilder indexBuilder, final IndexedEntry indexedEntry) {
322 // if (wikiTokenizer.token().equals("'''")) {
323 // insideTripleQuotes = !insideTripleQuotes;
325 final StringBuilder builder = new StringBuilder();
326 appendAndIndexWikiCallback.reset(builder, indexedEntry);
327 appendAndIndexWikiCallback.entryTypeName = EntryTypeName.WIKTIONARY_EXAMPLE;
328 appendAndIndexWikiCallback.entryTypeNameSticks = true;
330 // TODO: this is a hack needed because we don't safely split on the dash.
331 appendAndIndexWikiCallback.dispatch(example, indexBuilder, EntryTypeName.WIKTIONARY_EXAMPLE);
332 } catch (AssertionError e) {
335 final String result = trim(builder.toString());
336 return result.length() > 0 ? result : "--";