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 parser.parse(new BufferedInputStream(in), this);
101 } catch (Exception e) {
102 System.err.println("Exception during parse, lastPageTitle=" + lastPageTitle + ", titleBuilder=" + titleBuilder.toString());
107 for (final Selector selector : currentSelectors) {
108 selector.out.close();
114 String lastPageTitle = null;
116 private void endPage() {
117 final String title = titleBuilder.toString();
118 lastPageTitle = title;
119 if (++pageCount % 1000 == 0) {
120 System.out.println("endPage: " + title + ", count=" + pageCount);
122 if (title.startsWith("Wiktionary:") ||
123 title.startsWith("Appendix:") ||
124 title.startsWith("Help:") ||
125 title.startsWith("Index:") ||
126 title.startsWith("MediaWiki:") ||
127 title.startsWith("Citations:") ||
128 title.startsWith("Concordance:") ||
129 title.startsWith("Glossary:") ||
130 title.startsWith("Rhymes:") ||
131 title.startsWith("Category:") ||
132 title.startsWith("Wikisaurus:") ||
133 title.startsWith("Unsupported titles/") ||
134 title.startsWith("Transwiki:") ||
135 title.startsWith("File:") ||
136 title.startsWith("Thread:") ||
137 title.startsWith("Template:") ||
138 title.startsWith("Summary:") ||
139 title.startsWith("Module:") ||
141 title.startsWith("Datei:") ||
142 title.startsWith("Verzeichnis:") ||
143 title.startsWith("Vorlage:") ||
144 title.startsWith("Thesaurus:") ||
145 title.startsWith("Kategorie:") ||
146 title.startsWith("Hilfe:") ||
147 title.startsWith("Reim:") ||
149 title.startsWith("Annexe:") ||
150 title.startsWith("Catégori:") ||
151 title.startsWith("Modèle:") ||
152 title.startsWith("Thésaurus:") ||
153 title.startsWith("Projet:") ||
154 title.startsWith("Aide:") ||
155 title.startsWith("Fichier:") ||
156 title.startsWith("Wiktionnaire:") ||
157 title.startsWith("Catégorie:") ||
158 title.startsWith("Portail:") ||
159 title.startsWith("utiliusateur:") ||
160 title.startsWith("Kategorio:") ||
162 title.startsWith("Wikizionario:") ||
163 title.startsWith("Appendice:") ||
164 title.startsWith("Categoria:") ||
165 title.startsWith("Aiuto:") ||
166 title.startsWith("Portail:") ||
168 title.startsWith("Apéndice:") ||
169 title.startsWith("Archivo:") ||
170 title.startsWith("Ayuda:") ||
171 title.startsWith("Categoría:") ||
172 title.startsWith("Plantilla:") ||
173 title.startsWith("Wikcionario:") ||
180 if (title.contains(":")) {
181 if (!title.startsWith("Sign gloss:")) {
182 System.err.println("title with colon: " + title);
186 String text = textBuilder.toString();
187 String translingual = "";
189 while (text.length() > 0) {
191 final Matcher startMatcher = headingStart.matcher(text);
192 if (!startMatcher.find()) {
195 text = text.substring(startMatcher.end());
197 final String heading = startMatcher.group();
198 for (final Selector selector : currentSelectors) {
199 if (heading.indexOf("Translingual") != -1) {
201 final int depth = startMatcher.group(1).length();
202 final Pattern endPattern = Pattern.compile(String.format("^={1,%d}[^=].*$", depth), Pattern.MULTILINE);
204 final Matcher endMatcher = endPattern.matcher(text);
205 if (endMatcher.find()) {
206 int end = endMatcher.start();
207 translingual = text.substring(0, endMatcher.start());
208 text = text.substring(end);
212 if (selector.pattern.matcher(heading).find()) {
215 final int depth = startMatcher.group(1).length();
216 final Pattern endPattern = Pattern.compile(String.format("^={1,%d}[^=].*$", depth), Pattern.MULTILINE);
218 final Matcher endMatcher = endPattern.matcher(text);
220 if (endMatcher.find()) {
221 end = endMatcher.start();
226 String sectionText = text.substring(0, end);
227 // Hack to remove empty dummy section from French
228 if (sectionText.startsWith("\n=== {{S|étymologie}} ===\n: {{ébauche-étym")) {
229 int dummy_end = sectionText.indexOf("}}", 41) + 2;
230 while (dummy_end + 1 < sectionText.length() &&
231 sectionText.charAt(dummy_end) == '\n' &&
232 sectionText.charAt(dummy_end + 1) == '\n') ++dummy_end;
233 sectionText = sectionText.substring(dummy_end);
235 if (heading.indexOf("Japanese") == -1) sectionText += translingual;
236 final Section section = new Section(title, heading, sectionText);
239 selector.out.writeUTF(section.title);
240 selector.out.writeUTF(section.heading);
241 final byte[] bytes = section.text.getBytes("UTF8");
242 selector.out.writeInt(bytes.length);
243 selector.out.write(bytes);
244 } catch (IOException e) {
245 throw new RuntimeException(e);
248 text = text.substring(end);
256 // -----------------------------------------------------------------------
258 static class Section implements java.io.Serializable {
259 private static final long serialVersionUID = -7676549898325856822L;
262 final String heading;
265 public Section(final String title, final String heading, final String text) {
267 this.heading = heading;
270 //System.out.printf("TITLE:%s\nHEADING:%s\nTEXT:%s\n\n\n\n\n\n", title, heading, text);
274 static class Selector {
275 final String outFilename;
276 final Pattern pattern;
278 DataOutputStream out;
280 public Selector(final String filename, final String pattern) {
281 this.outFilename = filename;
282 this.pattern = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
286 // -----------------------------------------------------------------------
289 public void startElement(String uri, String localName, String qName,
290 Attributes attributes) {
291 currentBuilder = null;
292 if ("page".equals(qName)) {
293 titleBuilder = new StringBuilder();
295 // Start with "\n" to better match certain strings.
296 textBuilder = new StringBuilder("\n");
297 } else if ("title".equals(qName)) {
298 currentBuilder = titleBuilder;
299 } else if ("text".equals(qName)) {
300 currentBuilder = textBuilder;
305 public void characters(char[] ch, int start, int length) throws SAXException {
306 if (currentBuilder != null) {
307 currentBuilder.append(ch, start, length);
312 public void endElement(String uri, String localName, String qName)
313 throws SAXException {
314 currentBuilder = null;
315 if ("page".equals(qName)) {
320 public void parse(final File file) throws ParserConfigurationException,
321 SAXException, IOException {
322 final SAXParser parser = SAXParserFactoryImpl.newInstance().newSAXParser();
323 parser.parse(file, this);