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.nio.charset.StandardCharsets;
27 import java.util.ArrayList;
28 import java.util.LinkedHashMap;
29 import java.util.List;
31 import java.util.regex.Matcher;
32 import java.util.regex.Pattern;
34 import javax.xml.parsers.ParserConfigurationException;
35 import javax.xml.parsers.SAXParser;
36 import javax.xml.parsers.SAXParserFactory;
38 import org.apache.commons.compress.compressors.CompressorStreamFactory;
39 import org.xml.sax.Attributes;
40 import org.xml.sax.SAXException;
42 import com.hughes.android.dictionary.parser.wiktionary.WiktionaryLangs;
44 public class WiktionarySplitter extends org.xml.sax.helpers.DefaultHandler {
46 // The matches the whole line, otherwise regexes don't work well on French:
48 // Spanish has no initial headings, tried to also detect {{ES as such
49 // with "^(\\{\\{ES|(=+)[^=]).*$" but that broke English.
50 static final Matcher headingStart = Pattern.compile("^(=+)[^=].*$", Pattern.MULTILINE).matcher("");
51 static final Matcher startSpanish = Pattern.compile("\\{\\{ES(\\|[^{}=]*)?}}").matcher("");
53 final Map<String,List<Selector>> pathToSelectors = new LinkedHashMap<>();
54 List<Selector> currentSelectors = null;
56 StringBuilder titleBuilder;
57 StringBuilder textBuilder;
58 StringBuilder currentBuilder = null;
60 public static void main(final String[] args) throws Exception {
61 final WiktionarySplitter wiktionarySplitter = new WiktionarySplitter();
62 wiktionarySplitter.go();
65 private WiktionarySplitter() {
66 List<Selector> selectors;
67 for (final String code : WiktionaryLangs.wikiCodeToIsoCodeToWikiName.keySet()) {
68 //if (!code.equals("fr")) {continue;}
69 selectors = new ArrayList<>();
70 pathToSelectors.put(String.format("data/inputs/%swiktionary-pages-articles.xml", code), selectors);
71 for (final Map.Entry<String, String> entry : WiktionaryLangs.wikiCodeToIsoCodeToWikiName.get(code).entrySet()) {
72 final String dir = String.format("data/inputs/wikiSplit/%s", code);
73 new File(dir).mkdirs();
74 selectors.add(new Selector(String.format("%s/%s.data", dir, entry.getKey()), entry.getValue()));
79 private void go() throws Exception {
80 final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
83 for (final Map.Entry<String, List<Selector>> pathToSelectorsEntry : pathToSelectors.entrySet()) {
85 currentSelectors = pathToSelectorsEntry.getValue();
87 for (final Selector selector : currentSelectors) {
88 OutputStream tmp = new FileOutputStream(selector.outFilename + ".gz");
89 tmp = new BufferedOutputStream(tmp);
90 tmp = new CompressorStreamFactory().createCompressorOutputStream(CompressorStreamFactory.GZIP, tmp);
91 tmp = new WriteBuffer(tmp, 20 * 1024 * 1024);
92 selector.out = new DataOutputStream(tmp);
97 File input = new File(pathToSelectorsEntry.getKey() + ".bz2");
98 if (!input.exists()) input = new File(pathToSelectorsEntry.getKey() + ".gz");
99 if (!input.exists()) input = new File(pathToSelectorsEntry.getKey() + ".xz");
100 if (!input.exists()) {
101 // Fallback to uncompressed file
102 parser.parse(new File(pathToSelectorsEntry.getKey()), this);
104 InputStream compressedIn = new BufferedInputStream(new FileInputStream(input));
105 InputStream in = new CompressorStreamFactory().createCompressorInputStream(compressedIn);
106 in = new ReadAheadBuffer(in, 20 * 1024 * 1024);
107 parser.parse(new BufferedInputStream(in), this);
109 } catch (Exception e) {
110 System.err.println("Exception during parse, lastPageTitle=" + lastPageTitle + ", titleBuilder=" + titleBuilder + " of file " + pathToSelectorsEntry.getKey());
115 for (final Selector selector : currentSelectors) {
116 selector.out.close();
122 String lastPageTitle = null;
124 final Matcher[] endPatterns = new Matcher[100];
126 private Matcher getEndPattern(int depth) {
127 if (endPatterns[depth] == null)
128 endPatterns[depth] = Pattern.compile(String.format("^={1,%d}[^=].*$", depth), Pattern.MULTILINE).matcher("");
129 return endPatterns[depth];
132 private void endPage() {
133 final String title = titleBuilder.toString();
134 lastPageTitle = title;
135 if (++pageCount % 100000 == 0) {
136 System.out.println("endPage: " + title + ", count=" + pageCount);
138 if (title.startsWith("Unsupported titles/")) return;
139 if (title.contains(":")) {
140 if (title.startsWith("Wiktionary:") ||
141 title.startsWith("Appendix:") ||
142 title.startsWith("Help:") ||
143 title.startsWith("Index:") ||
144 title.startsWith("MediaWiki:") ||
145 title.startsWith("Citations:") ||
146 title.startsWith("Concordance:") ||
147 title.startsWith("Glossary:") ||
148 title.startsWith("Rhymes:") ||
149 title.startsWith("Category:") ||
150 title.startsWith("Wikisaurus:") ||
151 title.startsWith("Transwiki:") ||
152 title.startsWith("File:") ||
153 title.startsWith("Thread:") ||
154 title.startsWith("Template:") ||
155 title.startsWith("Summary:") ||
156 title.startsWith("Module:") ||
157 title.startsWith("Reconstruction:") ||
159 title.startsWith("Datei:") ||
160 title.startsWith("Verzeichnis:") ||
161 title.startsWith("Vorlage:") ||
162 title.startsWith("Thesaurus:") ||
163 title.startsWith("Kategorie:") ||
164 title.startsWith("Hilfe:") ||
165 title.startsWith("Reim:") ||
166 title.startsWith("Modul:") ||
168 title.startsWith("Annexe:") ||
169 title.startsWith("Catégori:") ||
170 title.startsWith("Modèle:") ||
171 title.startsWith("Thésaurus:") ||
172 title.startsWith("Projet:") ||
173 title.startsWith("Aide:") ||
174 title.startsWith("Fichier:") ||
175 title.startsWith("Wiktionnaire:") ||
176 title.startsWith("Translations:Wiktionnaire:") ||
177 title.startsWith("Translations:Projet:") ||
178 title.startsWith("Catégorie:") ||
179 title.startsWith("Portail:") ||
180 title.startsWith("utiliusateur:") ||
181 title.startsWith("Kategorio:") ||
182 title.startsWith("Tutoriel:") ||
184 title.startsWith("Wikizionario:") ||
185 title.startsWith("Appendice:") ||
186 title.startsWith("Categoria:") ||
187 title.startsWith("Aiuto:") ||
188 title.startsWith("Portail:") ||
189 title.startsWith("Modulo:") ||
191 title.startsWith("Apéndice:") ||
192 title.startsWith("Archivo:") ||
193 title.startsWith("Ayuda:") ||
194 title.startsWith("Categoría:") ||
195 title.startsWith("Plantilla:") ||
196 title.startsWith("Wikcionario:") ||
199 title.startsWith("Ajuda:") ||
200 title.startsWith("Apêndice:") ||
201 title.startsWith("Citações:") ||
202 title.startsWith("Portal:") ||
203 title.startsWith("Predefinição:") ||
204 title.startsWith("Vocabulário:") ||
205 title.startsWith("Wikcionário:") ||
206 title.startsWith("Módulo:") ||
211 // leave the Flexion: pages in for now and do not warn about them
212 if (!title.startsWith("Sign gloss:") && !title.startsWith("Flexion:")) {
213 System.err.println("title with colon: " + title);
217 String text = textBuilder.toString();
218 // Workaround for Spanish wiktionary {{ES}} and {{ES|word}} patterns
219 text = startSpanish.reset(text).replaceAll("== {{lengua|es}} ==");
220 String translingual = "";
222 headingStart.reset(text);
224 while (start < text.length()) {
226 if (!headingStart.find(start)) {
229 start = headingStart.end();
231 final String heading = headingStart.group();
233 // For Translingual entries just store the text for later
234 // use in the per-language sections
235 if (heading.contains("Translingual")) {
237 final int depth = headingStart.group(1).length();
238 final Matcher endMatcher = getEndPattern(depth).reset(text);
240 if (endMatcher.find(start)) {
241 int end = endMatcher.start();
242 translingual = text.substring(start, end);
248 for (final Selector selector : currentSelectors) {
249 if (selector.pattern.reset(heading).find()) {
251 final int depth = headingStart.group(1).length();
252 final Matcher endMatcher = getEndPattern(depth).reset(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.contains("Japanese")) 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(StandardCharsets.UTF_8);
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 Matcher 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).matcher("");
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) {
341 if (currentBuilder != null) {
342 currentBuilder.append(ch, start, length);
347 public void endElement(String uri, String localName, String qName) {
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);