]> gitweb.fperrin.net Git - DictionaryPC.git/blob - src/com/hughes/android/dictionary/engine/WiktionarySplitter.java
Cache compiled patterns.
[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     Pattern endPatterns[] = new Pattern[100];
118
119     private Pattern getEndPattern(int depth) {
120         if (endPatterns[depth] == null)
121             endPatterns[depth] = Pattern.compile(String.format("^={1,%d}[^=].*$", depth), Pattern.MULTILINE);
122         return endPatterns[depth];
123     }
124
125     private void endPage() {
126         final String title = titleBuilder.toString();
127         lastPageTitle = title;
128         if (++pageCount % 1000 == 0) {
129             System.out.println("endPage: " + title + ", count=" + pageCount);
130         }
131         if (title.startsWith("Wiktionary:") ||
132                 title.startsWith("Appendix:") ||
133                 title.startsWith("Help:") ||
134                 title.startsWith("Index:") ||
135                 title.startsWith("MediaWiki:") ||
136                 title.startsWith("Citations:") ||
137                 title.startsWith("Concordance:") ||
138                 title.startsWith("Glossary:") ||
139                 title.startsWith("Rhymes:") ||
140                 title.startsWith("Category:") ||
141                 title.startsWith("Wikisaurus:") ||
142                 title.startsWith("Unsupported titles/") ||
143                 title.startsWith("Transwiki:") ||
144                 title.startsWith("File:") ||
145                 title.startsWith("Thread:") ||
146                 title.startsWith("Template:") ||
147                 title.startsWith("Summary:") ||
148                 title.startsWith("Module:") ||
149                 // DE
150                 title.startsWith("Datei:") ||
151                 title.startsWith("Verzeichnis:") ||
152                 title.startsWith("Vorlage:") ||
153                 title.startsWith("Thesaurus:") ||
154                 title.startsWith("Kategorie:") ||
155                 title.startsWith("Hilfe:") ||
156                 title.startsWith("Reim:") ||
157                 // FR:
158                 title.startsWith("Annexe:") ||
159                 title.startsWith("Catégori:") ||
160                 title.startsWith("Modèle:") ||
161                 title.startsWith("Thésaurus:") ||
162                 title.startsWith("Projet:") ||
163                 title.startsWith("Aide:") ||
164                 title.startsWith("Fichier:") ||
165                 title.startsWith("Wiktionnaire:") ||
166                 title.startsWith("Catégorie:") ||
167                 title.startsWith("Portail:") ||
168                 title.startsWith("utiliusateur:") ||
169                 title.startsWith("Kategorio:") ||
170                 // IT
171                 title.startsWith("Wikizionario:") ||
172                 title.startsWith("Appendice:") ||
173                 title.startsWith("Categoria:") ||
174                 title.startsWith("Aiuto:") ||
175                 title.startsWith("Portail:") ||
176                 // ES
177                 title.startsWith("Apéndice:") ||
178                 title.startsWith("Archivo:") ||
179                 title.startsWith("Ayuda:") ||
180                 title.startsWith("Categoría:") ||
181                 title.startsWith("Plantilla:") ||
182                 title.startsWith("Wikcionario:") ||
183
184                 // sentinel
185                 false
186            ) {
187             return;
188         }
189         if (title.contains(":")) {
190             if (!title.startsWith("Sign gloss:")) {
191                 System.err.println("title with colon: " + title);
192             }
193         }
194
195         String text = textBuilder.toString();
196         String translingual = "";
197
198         while (text.length() > 0) {
199             // Find start.
200             final Matcher startMatcher = headingStart.matcher(text);
201             if (!startMatcher.find()) {
202                 return;
203             }
204             text = text.substring(startMatcher.end());
205
206             final String heading = startMatcher.group();
207             for (final Selector selector : currentSelectors) {
208                 if (heading.indexOf("Translingual") != -1) {
209                     // Find end.
210                     final int depth = startMatcher.group(1).length();
211                     final Pattern endPattern = getEndPattern(depth);
212
213                     final Matcher endMatcher = endPattern.matcher(text);
214                     if (endMatcher.find()) {
215                         int end = endMatcher.start();
216                         translingual = text.substring(0, endMatcher.start());
217                         text = text.substring(end);
218                         break;
219                     }
220                 }
221                 if (selector.pattern.matcher(heading).find()) {
222
223                     // Find end.
224                     final int depth = startMatcher.group(1).length();
225                     final Pattern endPattern = getEndPattern(depth);
226
227                     final Matcher endMatcher = endPattern.matcher(text);
228                     final int end;
229                     if (endMatcher.find()) {
230                         end = endMatcher.start();
231                     } else {
232                         end = text.length();
233                     }
234
235                     String sectionText = text.substring(0, end);
236                     // Hack to remove empty dummy section from French
237                     if (sectionText.startsWith("\n=== {{S|étymologie}} ===\n: {{ébauche-étym")) {
238                         int dummy_end = sectionText.indexOf("}}", 41) + 2;
239                         while (dummy_end + 1 < sectionText.length() &&
240                                 sectionText.charAt(dummy_end) == '\n' &&
241                                 sectionText.charAt(dummy_end + 1) == '\n') ++dummy_end;
242                         sectionText = sectionText.substring(dummy_end);
243                     }
244                     if (heading.indexOf("Japanese") == -1) sectionText += translingual;
245                     final Section section = new Section(title, heading, sectionText);
246
247                     try {
248                         selector.out.writeUTF(section.title);
249                         selector.out.writeUTF(section.heading);
250                         final byte[] bytes = section.text.getBytes("UTF8");
251                         selector.out.writeInt(bytes.length);
252                         selector.out.write(bytes);
253                     } catch (IOException e) {
254                         throw new RuntimeException(e);
255                     }
256
257                     text = text.substring(end);
258                     break;
259                 }
260             }
261         }
262
263     }
264
265     // -----------------------------------------------------------------------
266
267     static class Section implements java.io.Serializable {
268         private static final long serialVersionUID = -7676549898325856822L;
269
270         final String title;
271         final String heading;
272         final String text;
273
274         public Section(final String title, final String heading, final String text) {
275             this.title = title;
276             this.heading = heading;
277             this.text = text;
278
279             //System.out.printf("TITLE:%s\nHEADING:%s\nTEXT:%s\n\n\n\n\n\n", title, heading, text);
280         }
281     }
282
283     static class Selector {
284         final String outFilename;
285         final Pattern pattern;
286
287         DataOutputStream out;
288
289         public Selector(final String filename, final String pattern) {
290             this.outFilename = filename;
291             this.pattern = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
292         }
293     }
294
295     // -----------------------------------------------------------------------
296
297     @Override
298     public void startElement(String uri, String localName, String qName,
299                              Attributes attributes) {
300         currentBuilder = null;
301         if ("page".equals(qName)) {
302             titleBuilder = new StringBuilder();
303
304             // Start with "\n" to better match certain strings.
305             textBuilder = new StringBuilder("\n");
306         } else if ("title".equals(qName)) {
307             currentBuilder = titleBuilder;
308         } else if ("text".equals(qName)) {
309             currentBuilder = textBuilder;
310         }
311     }
312
313     @Override
314     public void characters(char[] ch, int start, int length) throws SAXException {
315         if (currentBuilder != null) {
316             currentBuilder.append(ch, start, length);
317         }
318     }
319
320     @Override
321     public void endElement(String uri, String localName, String qName)
322     throws SAXException {
323         currentBuilder = null;
324         if ("page".equals(qName)) {
325             endPage();
326         }
327     }
328
329     public void parse(final File file) throws ParserConfigurationException,
330         SAXException, IOException {
331         final SAXParser parser = SAXParserFactoryImpl.newInstance().newSAXParser();
332         parser.parse(file, this);
333     }
334
335 }