1 // Copyright 2011 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.engine;
17 import java.io.BufferedInputStream;
18 import java.io.BufferedOutputStream;
19 import java.io.DataOutputStream;
21 import java.io.FileInputStream;
22 import java.io.FileOutputStream;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.OutputStream;
26 import java.util.ArrayList;
27 import java.util.LinkedHashMap;
28 import java.util.List;
30 import java.util.regex.Matcher;
31 import java.util.regex.Pattern;
33 import javax.xml.parsers.ParserConfigurationException;
34 import javax.xml.parsers.SAXParser;
35 import javax.xml.parsers.SAXParserFactory;
37 import org.apache.commons.compress.compressors.CompressorStreamFactory;
38 import org.xml.sax.Attributes;
39 import org.xml.sax.SAXException;
41 import com.hughes.android.dictionary.parser.wiktionary.WiktionaryLangs;
43 public class WiktionarySplitter extends org.xml.sax.helpers.DefaultHandler {
45 // The matches the whole line, otherwise regexes don't work well on French:
47 // Spanish has no initial headings, tried to also detect {{ES as such
48 // with "^(\\{\\{ES|(=+)[^=]).*$" but that broke English.
49 static final Matcher headingStart = Pattern.compile("^(=+)[^=].*$", Pattern.MULTILINE).matcher("");
50 static final Matcher startSpanish = Pattern.compile("\\{\\{ES(\\|[^{}=]*)?}}").matcher("");
52 final Map<String,List<Selector>> pathToSelectors = new LinkedHashMap<String, List<Selector>>();
53 List<Selector> currentSelectors = null;
55 StringBuilder titleBuilder;
56 StringBuilder textBuilder;
57 StringBuilder currentBuilder = null;
59 public static void main(final String[] args) throws Exception {
60 final WiktionarySplitter wiktionarySplitter = new WiktionarySplitter();
61 wiktionarySplitter.go();
64 private WiktionarySplitter() {
65 List<Selector> selectors;
66 for (final String code : WiktionaryLangs.wikiCodeToIsoCodeToWikiName.keySet()) {
67 //if (!code.equals("fr")) {continue;}
68 selectors = new ArrayList<WiktionarySplitter.Selector>();
69 pathToSelectors.put(String.format("data/inputs/%swiktionary-pages-articles.xml", code), selectors);
70 for (final Map.Entry<String, String> entry : WiktionaryLangs.wikiCodeToIsoCodeToWikiName.get(code).entrySet()) {
71 final String dir = String.format("data/inputs/wikiSplit/%s", code);
72 new File(dir).mkdirs();
73 selectors.add(new Selector(String.format("%s/%s.data", dir, entry.getKey()), entry.getValue()));
78 private void go() throws Exception {
79 final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
82 for (final Map.Entry<String, List<Selector>> pathToSelectorsEntry : pathToSelectors.entrySet()) {
84 currentSelectors = pathToSelectorsEntry.getValue();
86 for (final Selector selector : currentSelectors) {
87 OutputStream tmp = new FileOutputStream(selector.outFilename + ".gz");
88 tmp = new BufferedOutputStream(tmp);
89 tmp = new CompressorStreamFactory().createCompressorOutputStream(CompressorStreamFactory.GZIP, tmp);
90 tmp = new WriteBuffer(tmp, 20 * 1024 * 1024);
91 selector.out = new DataOutputStream(tmp);
96 File input = new File(pathToSelectorsEntry.getKey() + ".bz2");
97 if (!input.exists()) input = new File(pathToSelectorsEntry.getKey() + ".gz");
98 if (!input.exists()) input = new File(pathToSelectorsEntry.getKey() + ".xz");
99 if (!input.exists()) {
100 // Fallback to uncompressed file
101 parser.parse(new File(pathToSelectorsEntry.getKey()), this);
103 InputStream compressedIn = new BufferedInputStream(new FileInputStream(input));
104 InputStream in = new CompressorStreamFactory().createCompressorInputStream(compressedIn);
105 in = new ReadAheadBuffer(in, 20 * 1024 * 1024);
106 parser.parse(new BufferedInputStream(in), this);
108 } catch (Exception e) {
109 System.err.println("Exception during parse, lastPageTitle=" + lastPageTitle + ", titleBuilder=" + titleBuilder.toString() + " of file " + pathToSelectorsEntry.getKey());
114 for (final Selector selector : currentSelectors) {
115 selector.out.close();
121 String lastPageTitle = null;
123 Matcher endPatterns[] = new Matcher[100];
125 private Matcher getEndPattern(int depth) {
126 if (endPatterns[depth] == null)
127 endPatterns[depth] = Pattern.compile(String.format("^={1,%d}[^=].*$", depth), Pattern.MULTILINE).matcher("");
128 return endPatterns[depth];
131 private void endPage() {
132 final String title = titleBuilder.toString();
133 lastPageTitle = title;
134 if (++pageCount % 100000 == 0) {
135 System.out.println("endPage: " + title + ", count=" + pageCount);
137 if (title.startsWith("Unsupported titles/")) return;
138 if (title.contains(":")) {
139 if (title.startsWith("Wiktionary:") ||
140 title.startsWith("Appendix:") ||
141 title.startsWith("Help:") ||
142 title.startsWith("Index:") ||
143 title.startsWith("MediaWiki:") ||
144 title.startsWith("Citations:") ||
145 title.startsWith("Concordance:") ||
146 title.startsWith("Glossary:") ||
147 title.startsWith("Rhymes:") ||
148 title.startsWith("Category:") ||
149 title.startsWith("Wikisaurus:") ||
150 title.startsWith("Transwiki:") ||
151 title.startsWith("File:") ||
152 title.startsWith("Thread:") ||
153 title.startsWith("Template:") ||
154 title.startsWith("Summary:") ||
155 title.startsWith("Module:") ||
156 title.startsWith("Reconstruction:") ||
158 title.startsWith("Datei:") ||
159 title.startsWith("Verzeichnis:") ||
160 title.startsWith("Vorlage:") ||
161 title.startsWith("Thesaurus:") ||
162 title.startsWith("Kategorie:") ||
163 title.startsWith("Hilfe:") ||
164 title.startsWith("Reim:") ||
165 title.startsWith("Modul:") ||
167 title.startsWith("Annexe:") ||
168 title.startsWith("Catégori:") ||
169 title.startsWith("Modèle:") ||
170 title.startsWith("Thésaurus:") ||
171 title.startsWith("Projet:") ||
172 title.startsWith("Aide:") ||
173 title.startsWith("Fichier:") ||
174 title.startsWith("Wiktionnaire:") ||
175 title.startsWith("Translations:Wiktionnaire:") ||
176 title.startsWith("Translations:Projet:") ||
177 title.startsWith("Catégorie:") ||
178 title.startsWith("Portail:") ||
179 title.startsWith("utiliusateur:") ||
180 title.startsWith("Kategorio:") ||
181 title.startsWith("Tutoriel:") ||
183 title.startsWith("Wikizionario:") ||
184 title.startsWith("Appendice:") ||
185 title.startsWith("Categoria:") ||
186 title.startsWith("Aiuto:") ||
187 title.startsWith("Portail:") ||
188 title.startsWith("Modulo:") ||
190 title.startsWith("Apéndice:") ||
191 title.startsWith("Archivo:") ||
192 title.startsWith("Ayuda:") ||
193 title.startsWith("Categoría:") ||
194 title.startsWith("Plantilla:") ||
195 title.startsWith("Wikcionario:") ||
198 title.startsWith("Ajuda:") ||
199 title.startsWith("Apêndice:") ||
200 title.startsWith("Citações:") ||
201 title.startsWith("Portal:") ||
202 title.startsWith("Predefinição:") ||
203 title.startsWith("Vocabulário:") ||
204 title.startsWith("Wikcionário:") ||
205 title.startsWith("Módulo:") ||
210 // leave the Flexion: pages in for now and do not warn about them
211 if (!title.startsWith("Sign gloss:") && !title.startsWith("Flexion:")) {
212 System.err.println("title with colon: " + title);
216 String text = textBuilder.toString();
217 // Workaround for Spanish wiktionary {{ES}} and {{ES|word}} patterns
218 text = startSpanish.reset(text).replaceAll("== {{lengua|es}} ==");
219 String translingual = "";
221 headingStart.reset(text);
223 while (start < text.length()) {
225 if (!headingStart.find(start)) {
228 start = headingStart.end();
230 final String heading = headingStart.group();
232 // For Translingual entries just store the text for later
233 // use in the per-language sections
234 if (heading.indexOf("Translingual") != -1) {
236 final int depth = headingStart.group(1).length();
237 final Matcher endMatcher = getEndPattern(depth).reset(text);
239 if (endMatcher.find(start)) {
240 int end = endMatcher.start();
241 translingual = text.substring(start, end);
247 for (final Selector selector : currentSelectors) {
248 if (selector.pattern.reset(heading).find()) {
250 final int depth = headingStart.group(1).length();
251 final Matcher endMatcher = getEndPattern(depth).reset(text);
254 if (endMatcher.find(start)) {
255 end = endMatcher.start();
260 String sectionText = text.substring(start, end);
261 // Hack to remove empty dummy section from French
262 if (sectionText.startsWith("\n=== {{S|étymologie}} ===\n: {{ébauche-étym")) {
263 int dummy_end = sectionText.indexOf("}}", 41) + 2;
264 while (dummy_end + 1 < sectionText.length() &&
265 sectionText.charAt(dummy_end) == '\n' &&
266 sectionText.charAt(dummy_end + 1) == '\n') ++dummy_end;
267 sectionText = sectionText.substring(dummy_end);
269 if (heading.indexOf("Japanese") == -1) sectionText += translingual;
270 final Section section = new Section(title, heading, sectionText);
273 selector.out.writeUTF(section.title);
274 selector.out.writeUTF(section.heading);
275 final byte[] bytes = section.text.getBytes("UTF8");
276 selector.out.writeInt(bytes.length);
277 selector.out.write(bytes);
278 } catch (IOException e) {
279 throw new RuntimeException(e);
290 // -----------------------------------------------------------------------
292 static class Section implements java.io.Serializable {
293 private static final long serialVersionUID = -7676549898325856822L;
296 final String heading;
299 public Section(final String title, final String heading, final String text) {
301 this.heading = heading;
304 //System.out.printf("TITLE:%s\nHEADING:%s\nTEXT:%s\n\n\n\n\n\n", title, heading, text);
308 static class Selector {
309 final String outFilename;
310 final Matcher pattern;
312 DataOutputStream out;
314 public Selector(final String filename, final String pattern) {
315 this.outFilename = filename;
316 this.pattern = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE).matcher("");
320 // -----------------------------------------------------------------------
323 public void startElement(String uri, String localName, String qName,
324 Attributes attributes) {
325 currentBuilder = null;
326 if ("page".equals(qName)) {
327 titleBuilder = new StringBuilder();
329 // Start with "\n" to better match certain strings.
330 textBuilder = new StringBuilder("\n");
331 } else if ("title".equals(qName)) {
332 currentBuilder = titleBuilder;
333 } else if ("text".equals(qName)) {
334 currentBuilder = textBuilder;
339 public void characters(char[] ch, int start, int length) throws SAXException {
340 if (currentBuilder != null) {
341 currentBuilder.append(ch, start, length);
346 public void endElement(String uri, String localName, String qName)
347 throws SAXException {
348 currentBuilder = null;
349 if ("page".equals(qName)) {
354 public void parse(final File file) throws ParserConfigurationException,
355 SAXException, IOException {
356 final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
357 parser.parse(file, this);