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 Pattern headingStart = Pattern.compile("^(=+)[^=].*$", Pattern.MULTILINE);
51 final Map<String,List<Selector>> pathToSelectors = new LinkedHashMap<String, List<Selector>>();
52 List<Selector> currentSelectors = null;
54 StringBuilder titleBuilder;
55 StringBuilder textBuilder;
56 StringBuilder currentBuilder = null;
58 public static void main(final String[] args) throws Exception {
59 final WiktionarySplitter wiktionarySplitter = new WiktionarySplitter();
60 wiktionarySplitter.go();
63 private WiktionarySplitter() {
64 List<Selector> selectors;
65 for (final String code : WiktionaryLangs.wikiCodeToIsoCodeToWikiName.keySet()) {
66 //if (!code.equals("fr")) {continue;}
67 selectors = new ArrayList<WiktionarySplitter.Selector>();
68 pathToSelectors.put(String.format("data/inputs/%swiktionary-pages-articles.xml", code), selectors);
69 for (final Map.Entry<String, String> entry : WiktionaryLangs.wikiCodeToIsoCodeToWikiName.get(code).entrySet()) {
70 final String dir = String.format("data/inputs/wikiSplit/%s", code);
71 new File(dir).mkdirs();
72 selectors.add(new Selector(String.format("%s/%s.data", dir, entry.getKey()), entry.getValue()));
77 private void go() throws Exception {
78 final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
81 for (final Map.Entry<String, List<Selector>> pathToSelectorsEntry : pathToSelectors.entrySet()) {
83 currentSelectors = pathToSelectorsEntry.getValue();
85 for (final Selector selector : currentSelectors) {
86 OutputStream tmp = new FileOutputStream(selector.outFilename + ".gz");
87 tmp = new BufferedOutputStream(tmp);
88 tmp = new CompressorStreamFactory().createCompressorOutputStream(CompressorStreamFactory.GZIP, tmp);
89 tmp = new WriteBuffer(tmp, 20 * 1024 * 1024);
90 selector.out = new DataOutputStream(tmp);
95 File input = new File(pathToSelectorsEntry.getKey() + ".bz2");
96 if (!input.exists()) input = new File(pathToSelectorsEntry.getKey() + ".gz");
97 if (!input.exists()) input = new File(pathToSelectorsEntry.getKey() + ".xz");
98 if (!input.exists()) {
99 // Fallback to uncompressed file
100 parser.parse(new File(pathToSelectorsEntry.getKey()), this);
102 InputStream compressedIn = new BufferedInputStream(new FileInputStream(input));
103 InputStream in = new CompressorStreamFactory().createCompressorInputStream(compressedIn);
104 in = new ReadAheadBuffer(in, 20 * 1024 * 1024);
105 parser.parse(new BufferedInputStream(in), this);
107 } catch (Exception e) {
108 System.err.println("Exception during parse, lastPageTitle=" + lastPageTitle + ", titleBuilder=" + titleBuilder.toString() + " of file " + pathToSelectorsEntry.getKey());
113 for (final Selector selector : currentSelectors) {
114 selector.out.close();
120 String lastPageTitle = null;
122 Pattern endPatterns[] = new Pattern[100];
124 private Pattern getEndPattern(int depth) {
125 if (endPatterns[depth] == null)
126 endPatterns[depth] = Pattern.compile(String.format("^={1,%d}[^=].*$", depth), Pattern.MULTILINE);
127 return endPatterns[depth];
130 private void endPage() {
131 final String title = titleBuilder.toString();
132 lastPageTitle = title;
133 if (++pageCount % 100000 == 0) {
134 System.out.println("endPage: " + title + ", count=" + pageCount);
136 if (title.startsWith("Unsupported titles/")) return;
137 if (title.contains(":")) {
138 if (title.startsWith("Wiktionary:") ||
139 title.startsWith("Appendix:") ||
140 title.startsWith("Help:") ||
141 title.startsWith("Index:") ||
142 title.startsWith("MediaWiki:") ||
143 title.startsWith("Citations:") ||
144 title.startsWith("Concordance:") ||
145 title.startsWith("Glossary:") ||
146 title.startsWith("Rhymes:") ||
147 title.startsWith("Category:") ||
148 title.startsWith("Wikisaurus:") ||
149 title.startsWith("Transwiki:") ||
150 title.startsWith("File:") ||
151 title.startsWith("Thread:") ||
152 title.startsWith("Template:") ||
153 title.startsWith("Summary:") ||
154 title.startsWith("Module:") ||
155 title.startsWith("Reconstruction:") ||
157 title.startsWith("Datei:") ||
158 title.startsWith("Verzeichnis:") ||
159 title.startsWith("Vorlage:") ||
160 title.startsWith("Thesaurus:") ||
161 title.startsWith("Kategorie:") ||
162 title.startsWith("Hilfe:") ||
163 title.startsWith("Reim:") ||
164 title.startsWith("Modul:") ||
166 title.startsWith("Annexe:") ||
167 title.startsWith("Catégori:") ||
168 title.startsWith("Modèle:") ||
169 title.startsWith("Thésaurus:") ||
170 title.startsWith("Projet:") ||
171 title.startsWith("Aide:") ||
172 title.startsWith("Fichier:") ||
173 title.startsWith("Wiktionnaire:") ||
174 title.startsWith("Translations:Wiktionnaire:") ||
175 title.startsWith("Translations:Projet:") ||
176 title.startsWith("Catégorie:") ||
177 title.startsWith("Portail:") ||
178 title.startsWith("utiliusateur:") ||
179 title.startsWith("Kategorio:") ||
180 title.startsWith("Tutoriel:") ||
182 title.startsWith("Wikizionario:") ||
183 title.startsWith("Appendice:") ||
184 title.startsWith("Categoria:") ||
185 title.startsWith("Aiuto:") ||
186 title.startsWith("Portail:") ||
187 title.startsWith("Modulo:") ||
189 title.startsWith("Apéndice:") ||
190 title.startsWith("Archivo:") ||
191 title.startsWith("Ayuda:") ||
192 title.startsWith("Categoría:") ||
193 title.startsWith("Plantilla:") ||
194 title.startsWith("Wikcionario:") ||
197 title.startsWith("Ajuda:") ||
198 title.startsWith("Apêndice:") ||
199 title.startsWith("Citações:") ||
200 title.startsWith("Portal:") ||
201 title.startsWith("Predefinição:") ||
202 title.startsWith("Vocabulário:") ||
203 title.startsWith("Wikcionário:") ||
204 title.startsWith("Módulo:") ||
209 // leave the Flexion: pages in for now and do not warn about them
210 if (!title.startsWith("Sign gloss:") && !title.startsWith("Flexion:")) {
211 System.err.println("title with colon: " + title);
215 String text = textBuilder.toString();
216 // Workaround for Spanish wiktionary {{ES}} and {{ES|word}} patterns
217 text = text.replaceAll("\\{\\{ES(\\|[^{}=]*)?}}", "== {{lengua|es}} ==");
218 String translingual = "";
220 final Matcher startMatcher = headingStart.matcher(text);
222 while (start < text.length()) {
224 if (!startMatcher.find(start)) {
227 start = startMatcher.end();
229 final String heading = startMatcher.group();
231 // For Translingual entries just store the text for later
232 // use in the per-language sections
233 if (heading.indexOf("Translingual") != -1) {
235 final int depth = startMatcher.group(1).length();
236 final Pattern endPattern = getEndPattern(depth);
238 final Matcher endMatcher = endPattern.matcher(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.matcher(heading).find()) {
250 final int depth = startMatcher.group(1).length();
251 final Pattern endPattern = getEndPattern(depth);
253 final Matcher endMatcher = endPattern.matcher(text);
255 if (endMatcher.find(start)) {
256 end = endMatcher.start();
261 String sectionText = text.substring(start, end);
262 // Hack to remove empty dummy section from French
263 if (sectionText.startsWith("\n=== {{S|étymologie}} ===\n: {{ébauche-étym")) {
264 int dummy_end = sectionText.indexOf("}}", 41) + 2;
265 while (dummy_end + 1 < sectionText.length() &&
266 sectionText.charAt(dummy_end) == '\n' &&
267 sectionText.charAt(dummy_end + 1) == '\n') ++dummy_end;
268 sectionText = sectionText.substring(dummy_end);
270 if (heading.indexOf("Japanese") == -1) sectionText += translingual;
271 final Section section = new Section(title, heading, sectionText);
274 selector.out.writeUTF(section.title);
275 selector.out.writeUTF(section.heading);
276 final byte[] bytes = section.text.getBytes("UTF8");
277 selector.out.writeInt(bytes.length);
278 selector.out.write(bytes);
279 } catch (IOException e) {
280 throw new RuntimeException(e);
291 // -----------------------------------------------------------------------
293 static class Section implements java.io.Serializable {
294 private static final long serialVersionUID = -7676549898325856822L;
297 final String heading;
300 public Section(final String title, final String heading, final String text) {
302 this.heading = heading;
305 //System.out.printf("TITLE:%s\nHEADING:%s\nTEXT:%s\n\n\n\n\n\n", title, heading, text);
309 static class Selector {
310 final String outFilename;
311 final Pattern pattern;
313 DataOutputStream out;
315 public Selector(final String filename, final String pattern) {
316 this.outFilename = filename;
317 this.pattern = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
321 // -----------------------------------------------------------------------
324 public void startElement(String uri, String localName, String qName,
325 Attributes attributes) {
326 currentBuilder = null;
327 if ("page".equals(qName)) {
328 titleBuilder = new StringBuilder();
330 // Start with "\n" to better match certain strings.
331 textBuilder = new StringBuilder("\n");
332 } else if ("title".equals(qName)) {
333 currentBuilder = titleBuilder;
334 } else if ("text".equals(qName)) {
335 currentBuilder = textBuilder;
340 public void characters(char[] ch, int start, int length) throws SAXException {
341 if (currentBuilder != null) {
342 currentBuilder.append(ch, start, length);
347 public void endElement(String uri, String localName, String qName)
348 throws SAXException {
349 currentBuilder = null;
350 if ("page".equals(qName)) {
355 public void parse(final File file) throws ParserConfigurationException,
356 SAXException, IOException {
357 final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
358 parser.parse(file, this);