]> gitweb.fperrin.net Git - DictionaryPC.git/blob - src/com/hughes/android/dictionary/engine/WiktionarySplitter.java
Add read-ahead buffer to decompress in parallel.
[DictionaryPC.git] / src / com / hughes / android / dictionary / engine / WiktionarySplitter.java
1 // Copyright 2011 Google Inc. All Rights Reserved.
2 //
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
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
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.
14
15 package com.hughes.android.dictionary.engine;
16
17 import java.io.BufferedInputStream;
18 import java.io.BufferedOutputStream;
19 import java.io.DataOutputStream;
20 import java.io.File;
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;
28 import java.util.Map;
29 import java.util.regex.Matcher;
30 import java.util.regex.Pattern;
31
32 import javax.xml.parsers.ParserConfigurationException;
33 import javax.xml.parsers.SAXParser;
34
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;
39
40 import com.hughes.android.dictionary.parser.wiktionary.WiktionaryLangs;
41
42 public class WiktionarySplitter extends org.xml.sax.helpers.DefaultHandler {
43
44     // The matches the whole line, otherwise regexes don't work well on French:
45     // {{=uk=}}
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);
49
50     final Map<String,List<Selector>> pathToSelectors = new LinkedHashMap<String, List<Selector>>();
51     List<Selector> currentSelectors = null;
52
53     StringBuilder titleBuilder;
54     StringBuilder textBuilder;
55     StringBuilder currentBuilder = null;
56
57     public static void main(final String[] args) throws Exception {
58         final WiktionarySplitter wiktionarySplitter = new WiktionarySplitter();
59         wiktionarySplitter.go();
60     }
61
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()));
72             }
73         }
74     }
75
76     private void go() throws Exception {
77         final SAXParser parser = SAXParserFactoryImpl.newInstance().newSAXParser();
78
79         // Configure things.
80         for (final Map.Entry<String, List<Selector>> pathToSelectorsEntry : pathToSelectors.entrySet()) {
81
82             currentSelectors = pathToSelectorsEntry.getValue();
83
84             for (final Selector selector : currentSelectors) {
85                 selector.out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(selector.outFilename)));
86             }
87
88             // Do it.
89             try {
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);
96                 } else {
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);
101                 }
102             } catch (Exception e) {
103                 System.err.println("Exception during parse, lastPageTitle=" + lastPageTitle + ", titleBuilder=" + titleBuilder.toString());
104                 throw e;
105             }
106
107             // Shutdown.
108             for (final Selector selector : currentSelectors) {
109                 selector.out.close();
110             }
111
112         }
113     }
114
115     String lastPageTitle = null;
116     int pageCount = 0;
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);
122         }
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:") ||
141                 // DE
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:") ||
149                 // FR:
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:") ||
162                 // IT
163                 title.startsWith("Wikizionario:") ||
164                 title.startsWith("Appendice:") ||
165                 title.startsWith("Categoria:") ||
166                 title.startsWith("Aiuto:") ||
167                 title.startsWith("Portail:") ||
168                 // ES
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:") ||
175
176                 // sentinel
177                 false
178            ) {
179             return;
180         }
181         if (title.contains(":")) {
182             if (!title.startsWith("Sign gloss:")) {
183                 System.err.println("title with colon: " + title);
184             }
185         }
186
187         String text = textBuilder.toString();
188         String translingual = "";
189
190         while (text.length() > 0) {
191             // Find start.
192             final Matcher startMatcher = headingStart.matcher(text);
193             if (!startMatcher.find()) {
194                 return;
195             }
196             text = text.substring(startMatcher.end());
197
198             final String heading = startMatcher.group();
199             for (final Selector selector : currentSelectors) {
200                 if (heading.indexOf("Translingual") != -1) {
201                     // Find end.
202                     final int depth = startMatcher.group(1).length();
203                     final Pattern endPattern = Pattern.compile(String.format("^={1,%d}[^=].*$", depth), Pattern.MULTILINE);
204
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);
210                         break;
211                     }
212                 }
213                 if (selector.pattern.matcher(heading).find()) {
214
215                     // Find end.
216                     final int depth = startMatcher.group(1).length();
217                     final Pattern endPattern = Pattern.compile(String.format("^={1,%d}[^=].*$", depth), Pattern.MULTILINE);
218
219                     final Matcher endMatcher = endPattern.matcher(text);
220                     final int end;
221                     if (endMatcher.find()) {
222                         end = endMatcher.start();
223                     } else {
224                         end = text.length();
225                     }
226
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);
235                     }
236                     if (heading.indexOf("Japanese") == -1) sectionText += translingual;
237                     final Section section = new Section(title, heading, sectionText);
238
239                     try {
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);
247                     }
248
249                     text = text.substring(end);
250                     break;
251                 }
252             }
253         }
254
255     }
256
257     // -----------------------------------------------------------------------
258
259     static class Section implements java.io.Serializable {
260         private static final long serialVersionUID = -7676549898325856822L;
261
262         final String title;
263         final String heading;
264         final String text;
265
266         public Section(final String title, final String heading, final String text) {
267             this.title = title;
268             this.heading = heading;
269             this.text = text;
270
271             //System.out.printf("TITLE:%s\nHEADING:%s\nTEXT:%s\n\n\n\n\n\n", title, heading, text);
272         }
273     }
274
275     static class Selector {
276         final String outFilename;
277         final Pattern pattern;
278
279         DataOutputStream out;
280
281         public Selector(final String filename, final String pattern) {
282             this.outFilename = filename;
283             this.pattern = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
284         }
285     }
286
287     // -----------------------------------------------------------------------
288
289     @Override
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();
295
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;
302         }
303     }
304
305     @Override
306     public void characters(char[] ch, int start, int length) throws SAXException {
307         if (currentBuilder != null) {
308             currentBuilder.append(ch, start, length);
309         }
310     }
311
312     @Override
313     public void endElement(String uri, String localName, String qName)
314     throws SAXException {
315         currentBuilder = null;
316         if ("page".equals(qName)) {
317             endPage();
318         }
319     }
320
321     public void parse(final File file) throws ParserConfigurationException,
322         SAXException, IOException {
323         final SAXParser parser = SAXParserFactoryImpl.newInstance().newSAXParser();
324         parser.parse(file, this);
325     }
326
327 }