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 (headingName.startsWith(" {{S|")) {
58 // HACK to support parsing frwiktionary
59 String[] parts = headingName.split("\\|");
60 if (parts.length > 2 && langCodePattern.matcher(parts[2]).find() &&
61 (parts.length < 4 || !parts[3].startsWith("flexion"))) {
62 doForeignPartOfSpeech(lang, headingName, wikiTokenizer.headingDepth(), wikiTokenizer);
64 } else if (partOfSpeechHeader.matcher(headingName).matches()) {
65 doForeignPartOfSpeech(lang, headingName, wikiTokenizer.headingDepth(), wikiTokenizer);
68 // It's not a heading.
69 // TODO: optimization: skip to next heading.
74 static final class ListSection {
75 final String firstPrefix;
76 final String firstLine;
77 final List<String> nextPrefixes = new ArrayList<String>();
78 final List<String> nextLines = new ArrayList<String>();
80 public ListSection(String firstPrefix, String firstLine) {
81 this.firstPrefix = firstPrefix;
82 this.firstLine = firstLine;
86 public String toString() {
87 return firstPrefix + firstLine + "{ " + nextPrefixes + "}";
92 private void doForeignPartOfSpeech(final String lang, String posHeading, final int posDepth, WikiTokenizer wikiTokenizer) {
93 if (++foreignCount % 1000 == 0) {
94 LOG.info("***" + lang + ", " + title + ", pos=" + posHeading + ", foreignCount=" + foreignCount);
96 if (title.equals("6")) {
100 final StringBuilder foreignBuilder = new StringBuilder();
101 final List<EnForeignParser.ListSection> listSections = new ArrayList<EnForeignParser.ListSection>();
103 appendAndIndexWikiCallback.reset(foreignBuilder, null);
104 this.state = State.ENGLISH_DEF_OF_FOREIGN; // TODO: this is wrong, need new category....
105 titleAppended = false;
110 EnForeignParser.ListSection lastListSection = null;
112 int currentHeadingDepth = posDepth;
113 while (wikiTokenizer.nextToken() != null) {
114 if (wikiTokenizer.isHeading()) {
115 currentHeadingDepth = wikiTokenizer.headingDepth();
117 if (currentHeadingDepth <= posDepth) {
118 wikiTokenizer.returnToLineStart();
123 if (currentHeadingDepth > posDepth) {
124 // TODO: deal with other neat info sections inside POS
128 if (wikiTokenizer.isFunction()) {
129 final String name = wikiTokenizer.functionName();
130 final List<String> args = wikiTokenizer.functionPositionArgs();
131 final Map<String,String> namedArgs = wikiTokenizer.functionNamedArgs();
132 // First line is generally a repeat of the title with some extra information.
133 // We need to build up the left side (foreign text, tokens) separately from the
134 // right side (English). The left-side may get paired with multiple right sides.
135 // The left side should get filed under every form of the word in question (singular, plural).
137 // For verbs, the conjugation comes later on in a deeper section.
138 // Ideally, we'd want to file every English entry with the verb
139 // under every verb form coming from the conjugation.
140 // Ie. under "fa": see: "make :: fare" and "do :: fare"
141 // But then where should we put the conjugation table?
142 // 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!)
143 // for the conjugation table from "fa".
144 // Would like to be able to link to a lang#token.
147 String head = namedArgs.remove("head");
148 final String tr = namedArgs.remove("tr");
149 if (head == null && tr != null && !titleAppended) {
153 final String form = appendAndIndexWikiCallback.dispatch(head, EntryTypeName.WIKTIONARY_TITLE_MULTI);
155 appendAndIndexWikiCallback.builder.append(" ");
156 titleAppended = true;
159 appendAndIndexWikiCallback.builder.append(" (");
160 final String form = appendAndIndexWikiCallback.dispatch(tr, EntryTypeName.WIKTIONARY_TRANSLITERATION);
162 appendAndIndexWikiCallback.builder.append(") ");
165 appendAndIndexWikiCallback.onFunction(wikiTokenizer, name, args, namedArgs);
167 } else if (wikiTokenizer.isListItem()) {
168 final String prefix = wikiTokenizer.listItemPrefix();
169 if (lastListSection != null &&
170 prefix.startsWith(lastListSection.firstPrefix) &&
171 prefix.length() > lastListSection.firstPrefix.length()) {
172 lastListSection.nextPrefixes.add(prefix);
173 lastListSection.nextLines.add(wikiTokenizer.listItemWikiText());
175 lastListSection = new ListSection(prefix, wikiTokenizer.listItemWikiText());
176 listSections.add(lastListSection);
178 } else if (lastListSection != null) {
179 // Don't append anything after the lists, because there's crap.
180 } else if (wikiTokenizer.isWikiLink()) {
182 foreignBuilder.append(wikiTokenizer.wikiLinkText());
184 } else if (wikiTokenizer.isPlainText()) {
186 foreignBuilder.append(wikiTokenizer.token());
187 } else if (wikiTokenizer.isHtml()) {
188 if (!wikiTokenizer.token().startsWith("<ref>")) {
189 foreignBuilder.append(wikiTokenizer.token());
191 } else if (wikiTokenizer.isMarkup() ||
192 wikiTokenizer.isNewline() ||
193 wikiTokenizer.isComment()) {
196 LOG.warning("Unexpected token: " + wikiTokenizer.token());
197 assert !wikiTokenizer.errors().isEmpty();
202 // Here's where we exit.
203 // Should we make an entry even if there are no foreign list items?
204 String foreign = foreignBuilder.toString().trim();
205 if (!titleAppended && !foreign.toLowerCase().startsWith(title.toLowerCase())) {
206 foreign = String.format("%s %s", title, foreign);
208 if (!langPattern.matcher(lang).matches()) {
209 foreign = String.format("(%s) %s", lang, foreign);
211 for (final EnForeignParser.ListSection listSection : listSections) {
212 doForeignListSection(foreign, title, wordForms, listSection);
217 private void doForeignListSection(final String foreignText, String title, final Collection<String> forms, final EnForeignParser.ListSection listSection) {
218 state = State.ENGLISH_DEF_OF_FOREIGN;
219 final String prefix = listSection.firstPrefix;
220 if (prefix.length() > 1) {
221 // Could just get looser and say that any prefix longer than first is a sublist.
222 LOG.warning("Prefix '" + prefix + "' too long: " + listSection);
223 incrementCount("WARNING: Prefix too long");
227 final PairEntry pairEntry = new PairEntry(entrySource);
228 final IndexedEntry indexedEntry = new IndexedEntry(pairEntry);
229 indexedEntry.isValid = true;
231 entryIsFormOfSomething = false;
232 final StringBuilder englishBuilder = new StringBuilder();
233 final String mainLine = listSection.firstLine;
234 appendAndIndexWikiCallback.reset(englishBuilder, indexedEntry);
235 appendAndIndexWikiCallback.dispatch(mainLine, enIndexBuilder, EntryTypeName.WIKTIONARY_ENGLISH_DEF);
237 final String english = trim(englishBuilder.toString());
238 if (english.length() > 0) {
239 final Pair pair = new Pair(english, trim(foreignText), this.swap);
240 pairEntry.pairs.add(pair);
241 foreignIndexBuilder.addEntryWithString(indexedEntry, title, entryIsFormOfSomething ? EntryTypeName.WIKTIONARY_IS_FORM_OF_SOMETHING_ELSE : EntryTypeName.WIKTIONARY_TITLE_MULTI);
242 for (final String form : forms) {
243 foreignIndexBuilder.addEntryWithString(indexedEntry, form, EntryTypeName.WIKTIONARY_INFLECTED_FORM_MULTI);
248 String lastForeign = null;
249 for (int i = 0; i < listSection.nextPrefixes.size(); ++i) {
250 final String nextPrefix = listSection.nextPrefixes.get(i);
251 String nextLine = listSection.nextLines.get(i);
253 // TODO: This splitting is not sensitive to wiki code.
254 int dash = nextLine.indexOf("—");
257 dash = nextLine.indexOf("—");
261 dash = nextLine.indexOf(" - ");
265 if ((nextPrefix.equals("#:") || nextPrefix.equals("##:")) && dash != -1) {
266 final String foreignEx = nextLine.substring(0, dash);
267 final String englishEx = nextLine.substring(dash + mdashLen);
268 final Pair pair = new Pair(formatAndIndexExampleString(englishEx, enIndexBuilder, indexedEntry), formatAndIndexExampleString(foreignEx, foreignIndexBuilder, indexedEntry), swap);
269 if (pair.lang1 != "--" && pair.lang1 != "--") {
270 pairEntry.pairs.add(pair);
273 // TODO: make #* and #*: work
274 } else if (nextPrefix.equals("#:") || nextPrefix.equals("##:")/* || nextPrefix.equals("#*")*/){
275 final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
276 lastForeign = nextLine;
277 if (pair.lang1 != "--" && pair.lang1 != "--") {
278 pairEntry.pairs.add(pair);
280 } else if (nextPrefix.equals("#::") || nextPrefix.equals("#**")/* || nextPrefix.equals("#*:")*/) {
281 if (lastForeign != null && pairEntry.pairs.size() > 0) {
282 if (i + 1 < listSection.nextPrefixes.size()) {
283 // Chinese has sometimes multiple foreign lines
284 final String nextNextPrefix = listSection.nextPrefixes.get(i + 1);
285 if (nextNextPrefix.equals("#::") || nextNextPrefix.equals("#**")) {
287 nextLine += "\n" + listSection.nextLines.get(i);
290 pairEntry.pairs.remove(pairEntry.pairs.size() - 1);
291 final Pair pair = new Pair(formatAndIndexExampleString(nextLine, enIndexBuilder, indexedEntry), formatAndIndexExampleString(lastForeign, foreignIndexBuilder, indexedEntry), swap);
292 if (pair.lang1 != "--" || pair.lang2 != "--") {
293 pairEntry.pairs.add(pair);
297 LOG.warning("TODO: English example with no foreign: " + title + ", " + nextLine);
298 final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
299 if (pair.lang1 != "--" || pair.lang2 != "--") {
300 pairEntry.pairs.add(pair);
303 } else if (nextPrefix.equals("#*")) {
304 // Can't really index these.
305 final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
306 lastForeign = nextLine;
307 if (pair.lang1 != "--" || pair.lang2 != "--") {
308 pairEntry.pairs.add(pair);
310 } else if (nextPrefix.equals("#::*") || nextPrefix.equals("##") || nextPrefix.equals("#*:") || nextPrefix.equals("#:*") || true) {
311 final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
312 if (pair.lang1 != "--" || pair.lang2 != "--") {
313 pairEntry.pairs.add(pair);
321 private String formatAndIndexExampleString(final String example, final IndexBuilder indexBuilder, final IndexedEntry indexedEntry) {
323 // if (wikiTokenizer.token().equals("'''")) {
324 // insideTripleQuotes = !insideTripleQuotes;
326 final StringBuilder builder = new StringBuilder();
327 appendAndIndexWikiCallback.reset(builder, indexedEntry);
328 appendAndIndexWikiCallback.entryTypeName = EntryTypeName.WIKTIONARY_EXAMPLE;
329 appendAndIndexWikiCallback.entryTypeNameSticks = true;
331 // TODO: this is a hack needed because we don't safely split on the dash.
332 appendAndIndexWikiCallback.dispatch(example, indexBuilder, EntryTypeName.WIKTIONARY_EXAMPLE);
333 } catch (AssertionError e) {
336 final String result = trim(builder.toString());
337 return result.length() > 0 ? result : "--";