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.InputStream;
24 import java.io.IOException;
25 import java.util.ArrayList;
26 import java.util.LinkedHashMap;
27 import java.util.List;
29 import java.util.regex.Matcher;
30 import java.util.regex.Pattern;
32 import javax.xml.parsers.ParserConfigurationException;
33 import javax.xml.parsers.SAXParser;
35 import org.apache.xerces.jaxp.SAXParserFactoryImpl;
36 import org.apache.commons.compress.compressors.CompressorStreamFactory;
37 import org.xml.sax.Attributes;
38 import org.xml.sax.SAXException;
40 import com.hughes.android.dictionary.parser.wiktionary.WiktionaryLangs;
42 public class WiktionarySplitter extends org.xml.sax.helpers.DefaultHandler {
44 // The matches the whole line, otherwise regexes don't work well on French:
46 // Spanish has no initial headings, tried to also detect {{ES as such
47 // with "^(\\{\\{ES|(=+)[^=]).*$" but that broke English.
48 static final Pattern headingStart = Pattern.compile("^(=+)[^=].*$", Pattern.MULTILINE);
50 final Map<String,List<Selector>> pathToSelectors = new LinkedHashMap<String, List<Selector>>();
51 List<Selector> currentSelectors = null;
53 StringBuilder titleBuilder;
54 StringBuilder textBuilder;
55 StringBuilder currentBuilder = null;
57 public static void main(final String[] args) throws Exception {
58 final WiktionarySplitter wiktionarySplitter = new WiktionarySplitter();
59 wiktionarySplitter.go();
62 private WiktionarySplitter() {
63 List<Selector> selectors;
64 for (final String code : WiktionaryLangs.wikiCodeToIsoCodeToWikiName.keySet()) {
65 //if (!code.equals("fr")) {continue;}
66 selectors = new ArrayList<WiktionarySplitter.Selector>();
67 pathToSelectors.put(String.format("data/inputs/%swiktionary-pages-articles.xml", code), selectors);
68 for (final Map.Entry<String, String> entry : WiktionaryLangs.wikiCodeToIsoCodeToWikiName.get(code).entrySet()) {
69 final String dir = String.format("data/inputs/wikiSplit/%s", code);
70 new File(dir).mkdirs();
71 selectors.add(new Selector(String.format("%s/%s.data", dir, entry.getKey()), entry.getValue()));
76 private void go() throws Exception {
77 final SAXParser parser = SAXParserFactoryImpl.newInstance().newSAXParser();
80 for (final Map.Entry<String, List<Selector>> pathToSelectorsEntry : pathToSelectors.entrySet()) {
82 currentSelectors = pathToSelectorsEntry.getValue();
84 for (final Selector selector : currentSelectors) {
85 selector.out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(selector.outFilename)));
90 File input = new File(pathToSelectorsEntry.getKey() + ".bz2");
91 if (!input.exists()) input = new File(pathToSelectorsEntry.getKey() + ".gz");
92 if (!input.exists()) input = new File(pathToSelectorsEntry.getKey() + ".xz");
93 if (!input.exists()) {
94 // Fallback to uncompressed file
95 parser.parse(new File(pathToSelectorsEntry.getKey()), this);
97 InputStream compressedIn = new BufferedInputStream(new FileInputStream(input));
98 InputStream in = new CompressorStreamFactory().createCompressorInputStream(compressedIn);
99 in = new ReadAheadBuffer(in, 20 * 1024 * 1024);
100 parser.parse(new BufferedInputStream(in), this);
102 } catch (Exception e) {
103 System.err.println("Exception during parse, lastPageTitle=" + lastPageTitle + ", titleBuilder=" + titleBuilder.toString());
108 for (final Selector selector : currentSelectors) {
109 selector.out.close();
115 String lastPageTitle = null;
117 private void endPage() {
118 final String title = titleBuilder.toString();
119 lastPageTitle = title;
120 if (++pageCount % 1000 == 0) {
121 System.out.println("endPage: " + title + ", count=" + pageCount);
123 if (title.startsWith("Wiktionary:") ||
124 title.startsWith("Appendix:") ||
125 title.startsWith("Help:") ||
126 title.startsWith("Index:") ||
127 title.startsWith("MediaWiki:") ||
128 title.startsWith("Citations:") ||
129 title.startsWith("Concordance:") ||
130 title.startsWith("Glossary:") ||
131 title.startsWith("Rhymes:") ||
132 title.startsWith("Category:") ||
133 title.startsWith("Wikisaurus:") ||
134 title.startsWith("Unsupported titles/") ||
135 title.startsWith("Transwiki:") ||
136 title.startsWith("File:") ||
137 title.startsWith("Thread:") ||
138 title.startsWith("Template:") ||
139 title.startsWith("Summary:") ||
140 title.startsWith("Module:") ||
142 title.startsWith("Datei:") ||
143 title.startsWith("Verzeichnis:") ||
144 title.startsWith("Vorlage:") ||
145 title.startsWith("Thesaurus:") ||
146 title.startsWith("Kategorie:") ||
147 title.startsWith("Hilfe:") ||
148 title.startsWith("Reim:") ||
150 title.startsWith("Annexe:") ||
151 title.startsWith("Catégori:") ||
152 title.startsWith("Modèle:") ||
153 title.startsWith("Thésaurus:") ||
154 title.startsWith("Projet:") ||
155 title.startsWith("Aide:") ||
156 title.startsWith("Fichier:") ||
157 title.startsWith("Wiktionnaire:") ||
158 title.startsWith("Catégorie:") ||
159 title.startsWith("Portail:") ||
160 title.startsWith("utiliusateur:") ||
161 title.startsWith("Kategorio:") ||
163 title.startsWith("Wikizionario:") ||
164 title.startsWith("Appendice:") ||
165 title.startsWith("Categoria:") ||
166 title.startsWith("Aiuto:") ||
167 title.startsWith("Portail:") ||
169 title.startsWith("Apéndice:") ||
170 title.startsWith("Archivo:") ||
171 title.startsWith("Ayuda:") ||
172 title.startsWith("Categoría:") ||
173 title.startsWith("Plantilla:") ||
174 title.startsWith("Wikcionario:") ||
181 if (title.contains(":")) {
182 if (!title.startsWith("Sign gloss:")) {
183 System.err.println("title with colon: " + title);
187 String text = textBuilder.toString();
188 String translingual = "";
190 while (text.length() > 0) {
192 final Matcher startMatcher = headingStart.matcher(text);
193 if (!startMatcher.find()) {
196 text = text.substring(startMatcher.end());
198 final String heading = startMatcher.group();
199 for (final Selector selector : currentSelectors) {
200 if (heading.indexOf("Translingual") != -1) {
202 final int depth = startMatcher.group(1).length();
203 final Pattern endPattern = Pattern.compile(String.format("^={1,%d}[^=].*$", depth), Pattern.MULTILINE);
205 final Matcher endMatcher = endPattern.matcher(text);
206 if (endMatcher.find()) {
207 int end = endMatcher.start();
208 translingual = text.substring(0, endMatcher.start());
209 text = text.substring(end);
213 if (selector.pattern.matcher(heading).find()) {
216 final int depth = startMatcher.group(1).length();
217 final Pattern endPattern = Pattern.compile(String.format("^={1,%d}[^=].*$", depth), Pattern.MULTILINE);
219 final Matcher endMatcher = endPattern.matcher(text);
221 if (endMatcher.find()) {
222 end = endMatcher.start();
227 String sectionText = text.substring(0, end);
228 // Hack to remove empty dummy section from French
229 if (sectionText.startsWith("\n=== {{S|étymologie}} ===\n: {{ébauche-étym")) {
230 int dummy_end = sectionText.indexOf("}}", 41) + 2;
231 while (dummy_end + 1 < sectionText.length() &&
232 sectionText.charAt(dummy_end) == '\n' &&
233 sectionText.charAt(dummy_end + 1) == '\n') ++dummy_end;
234 sectionText = sectionText.substring(dummy_end);
236 if (heading.indexOf("Japanese") == -1) sectionText += translingual;
237 final Section section = new Section(title, heading, sectionText);
240 selector.out.writeUTF(section.title);
241 selector.out.writeUTF(section.heading);
242 final byte[] bytes = section.text.getBytes("UTF8");
243 selector.out.writeInt(bytes.length);
244 selector.out.write(bytes);
245 } catch (IOException e) {
246 throw new RuntimeException(e);
249 text = text.substring(end);
257 // -----------------------------------------------------------------------
259 static class Section implements java.io.Serializable {
260 private static final long serialVersionUID = -7676549898325856822L;
263 final String heading;
266 public Section(final String title, final String heading, final String text) {
268 this.heading = heading;
271 //System.out.printf("TITLE:%s\nHEADING:%s\nTEXT:%s\n\n\n\n\n\n", title, heading, text);
275 static class Selector {
276 final String outFilename;
277 final Pattern pattern;
279 DataOutputStream out;
281 public Selector(final String filename, final String pattern) {
282 this.outFilename = filename;
283 this.pattern = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
287 // -----------------------------------------------------------------------
290 public void startElement(String uri, String localName, String qName,
291 Attributes attributes) {
292 currentBuilder = null;
293 if ("page".equals(qName)) {
294 titleBuilder = new StringBuilder();
296 // Start with "\n" to better match certain strings.
297 textBuilder = new StringBuilder("\n");
298 } else if ("title".equals(qName)) {
299 currentBuilder = titleBuilder;
300 } else if ("text".equals(qName)) {
301 currentBuilder = textBuilder;
306 public void characters(char[] ch, int start, int length) throws SAXException {
307 if (currentBuilder != null) {
308 currentBuilder.append(ch, start, length);
313 public void endElement(String uri, String localName, String qName)
314 throws SAXException {
315 currentBuilder = null;
316 if ("page".equals(qName)) {
321 public void parse(final File file) throws ParserConfigurationException,
322 SAXException, IOException {
323 final SAXParser parser = SAXParserFactoryImpl.newInstance().newSAXParser();
324 parser.parse(file, this);