]> gitweb.fperrin.net Git - DictionaryPC.git/blob - src/com/hughes/android/dictionary/engine/WiktionarySplitter.java
ed17fb5bf55c4f72f3bcc4dfe5d30f9a37cb98b4
[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.IOException;
24 import java.io.InputStream;
25 import java.io.OutputStream;
26 import java.util.ArrayList;
27 import java.util.LinkedHashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.regex.Matcher;
31 import java.util.regex.Pattern;
32
33 import javax.xml.parsers.ParserConfigurationException;
34 import javax.xml.parsers.SAXParser;
35 import javax.xml.parsers.SAXParserFactory;
36
37 import org.apache.commons.compress.compressors.CompressorStreamFactory;
38 import org.xml.sax.Attributes;
39 import org.xml.sax.SAXException;
40
41 import com.hughes.android.dictionary.parser.wiktionary.WiktionaryLangs;
42
43 public class WiktionarySplitter extends org.xml.sax.helpers.DefaultHandler {
44
45     // The matches the whole line, otherwise regexes don't work well on French:
46     // {{=uk=}}
47     // Spanish has no initial headings, tried to also detect {{ES as such
48     // with "^(\\{\\{ES|(=+)[^=]).*$" but that broke English.
49     static final Matcher headingStart = Pattern.compile("^(=+)[^=].*$", Pattern.MULTILINE).matcher("");
50     static final Matcher startSpanish = Pattern.compile("\\{\\{ES(\\|[^{}=]*)?}}").matcher("");
51
52     final Map<String,List<Selector>> pathToSelectors = new LinkedHashMap<String, List<Selector>>();
53     List<Selector> currentSelectors = null;
54
55     StringBuilder titleBuilder;
56     StringBuilder textBuilder;
57     StringBuilder currentBuilder = null;
58
59     public static void main(final String[] args) throws Exception {
60         final WiktionarySplitter wiktionarySplitter = new WiktionarySplitter();
61         wiktionarySplitter.go();
62     }
63
64     private WiktionarySplitter() {
65         List<Selector> selectors;
66         for (final String code : WiktionaryLangs.wikiCodeToIsoCodeToWikiName.keySet()) {
67             //if (!code.equals("fr")) {continue;}
68             selectors = new ArrayList<WiktionarySplitter.Selector>();
69             pathToSelectors.put(String.format("data/inputs/%swiktionary-pages-articles.xml", code), selectors);
70             for (final Map.Entry<String, String> entry : WiktionaryLangs.wikiCodeToIsoCodeToWikiName.get(code).entrySet()) {
71                 final String dir = String.format("data/inputs/wikiSplit/%s", code);
72                 new File(dir).mkdirs();
73                 selectors.add(new Selector(String.format("%s/%s.data", dir, entry.getKey()), entry.getValue()));
74             }
75         }
76     }
77
78     private void go() throws Exception {
79         final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
80
81         // Configure things.
82         for (final Map.Entry<String, List<Selector>> pathToSelectorsEntry : pathToSelectors.entrySet()) {
83
84             currentSelectors = pathToSelectorsEntry.getValue();
85
86             for (final Selector selector : currentSelectors) {
87                 OutputStream tmp = new FileOutputStream(selector.outFilename + ".gz");
88                 tmp = new BufferedOutputStream(tmp);
89                 tmp = new CompressorStreamFactory().createCompressorOutputStream(CompressorStreamFactory.GZIP, tmp);
90                 tmp = new WriteBuffer(tmp, 20 * 1024 * 1024);
91                 selector.out = new DataOutputStream(tmp);
92             }
93
94             // Do it.
95             try {
96                 File input = new File(pathToSelectorsEntry.getKey() + ".bz2");
97                 if (!input.exists()) input = new File(pathToSelectorsEntry.getKey() + ".gz");
98                 if (!input.exists()) input = new File(pathToSelectorsEntry.getKey() + ".xz");
99                 if (!input.exists()) {
100                     // Fallback to uncompressed file
101                     parser.parse(new File(pathToSelectorsEntry.getKey()), this);
102                 } else {
103                     InputStream compressedIn = new BufferedInputStream(new FileInputStream(input));
104                     InputStream in = new CompressorStreamFactory().createCompressorInputStream(compressedIn);
105                     in = new ReadAheadBuffer(in, 20 * 1024 * 1024);
106                     parser.parse(new BufferedInputStream(in), this);
107                 }
108             } catch (Exception e) {
109                 System.err.println("Exception during parse, lastPageTitle=" + lastPageTitle + ", titleBuilder=" + titleBuilder.toString() + " of file " + pathToSelectorsEntry.getKey());
110                 throw e;
111             }
112
113             // Shutdown.
114             for (final Selector selector : currentSelectors) {
115                 selector.out.close();
116             }
117
118         }
119     }
120
121     String lastPageTitle = null;
122     int pageCount = 0;
123     Matcher endPatterns[] = new Matcher[100];
124
125     private Matcher getEndPattern(int depth) {
126         if (endPatterns[depth] == null)
127             endPatterns[depth] = Pattern.compile(String.format("^={1,%d}[^=].*$", depth), Pattern.MULTILINE).matcher("");
128         return endPatterns[depth];
129     }
130
131     private void endPage() {
132         final String title = titleBuilder.toString();
133         lastPageTitle = title;
134         if (++pageCount % 100000 == 0) {
135             System.out.println("endPage: " + title + ", count=" + pageCount);
136         }
137         if (title.startsWith("Unsupported titles/")) return;
138         if (title.contains(":")) {
139             if (title.startsWith("Wiktionary:") ||
140                 title.startsWith("Appendix:") ||
141                 title.startsWith("Help:") ||
142                 title.startsWith("Index:") ||
143                 title.startsWith("MediaWiki:") ||
144                 title.startsWith("Citations:") ||
145                 title.startsWith("Concordance:") ||
146                 title.startsWith("Glossary:") ||
147                 title.startsWith("Rhymes:") ||
148                 title.startsWith("Category:") ||
149                 title.startsWith("Wikisaurus:") ||
150                 title.startsWith("Transwiki:") ||
151                 title.startsWith("File:") ||
152                 title.startsWith("Thread:") ||
153                 title.startsWith("Template:") ||
154                 title.startsWith("Summary:") ||
155                 title.startsWith("Module:") ||
156                 title.startsWith("Reconstruction:") ||
157                 // DE
158                 title.startsWith("Datei:") ||
159                 title.startsWith("Verzeichnis:") ||
160                 title.startsWith("Vorlage:") ||
161                 title.startsWith("Thesaurus:") ||
162                 title.startsWith("Kategorie:") ||
163                 title.startsWith("Hilfe:") ||
164                 title.startsWith("Reim:") ||
165                 title.startsWith("Modul:") ||
166                 // FR:
167                 title.startsWith("Annexe:") ||
168                 title.startsWith("Catégori:") ||
169                 title.startsWith("Modèle:") ||
170                 title.startsWith("Thésaurus:") ||
171                 title.startsWith("Projet:") ||
172                 title.startsWith("Aide:") ||
173                 title.startsWith("Fichier:") ||
174                 title.startsWith("Wiktionnaire:") ||
175                 title.startsWith("Translations:Wiktionnaire:") ||
176                 title.startsWith("Translations:Projet:") ||
177                 title.startsWith("Catégorie:") ||
178                 title.startsWith("Portail:") ||
179                 title.startsWith("utiliusateur:") ||
180                 title.startsWith("Kategorio:") ||
181                 title.startsWith("Tutoriel:") ||
182                 // IT
183                 title.startsWith("Wikizionario:") ||
184                 title.startsWith("Appendice:") ||
185                 title.startsWith("Categoria:") ||
186                 title.startsWith("Aiuto:") ||
187                 title.startsWith("Portail:") ||
188                 title.startsWith("Modulo:") ||
189                 // ES
190                 title.startsWith("Apéndice:") ||
191                 title.startsWith("Archivo:") ||
192                 title.startsWith("Ayuda:") ||
193                 title.startsWith("Categoría:") ||
194                 title.startsWith("Plantilla:") ||
195                 title.startsWith("Wikcionario:") ||
196
197                 // PT
198                 title.startsWith("Ajuda:") ||
199                 title.startsWith("Apêndice:") ||
200                 title.startsWith("Citações:") ||
201                 title.startsWith("Portal:") ||
202                 title.startsWith("Predefinição:") ||
203                 title.startsWith("Vocabulário:") ||
204                 title.startsWith("Wikcionário:") ||
205                 title.startsWith("Módulo:") ||
206
207                 // sentinel
208                 false
209                ) return;
210             // leave the Flexion: pages in for now and do not warn about them
211             if (!title.startsWith("Sign gloss:") && !title.startsWith("Flexion:")) {
212                 System.err.println("title with colon: " + title);
213             }
214         }
215
216         String text = textBuilder.toString();
217         // Workaround for Spanish wiktionary {{ES}} and {{ES|word}} patterns
218         text = startSpanish.reset(text).replaceAll("== {{lengua|es}} ==");
219         String translingual = "";
220         int start = 0;
221         headingStart.reset(text);
222
223         while (start < text.length()) {
224             // Find start.
225             if (!headingStart.find(start)) {
226                 return;
227             }
228             start = headingStart.end();
229
230             final String heading = headingStart.group();
231
232             // For Translingual entries just store the text for later
233             // use in the per-language sections
234             if (heading.indexOf("Translingual") != -1) {
235                 // Find end.
236                 final int depth = headingStart.group(1).length();
237                 final Matcher endMatcher = getEndPattern(depth).reset(text);
238
239                 if (endMatcher.find(start)) {
240                     int end = endMatcher.start();
241                     translingual = text.substring(start, end);
242                     start = end;
243                     continue;
244                 }
245             }
246
247             for (final Selector selector : currentSelectors) {
248                 if (selector.pattern.reset(heading).find()) {
249                     // Find end.
250                     final int depth = headingStart.group(1).length();
251                     final Matcher endMatcher = getEndPattern(depth).reset(text);
252
253                     final int end;
254                     if (endMatcher.find(start)) {
255                         end = endMatcher.start();
256                     } else {
257                         end = text.length();
258                     }
259
260                     String sectionText = text.substring(start, end);
261                     // Hack to remove empty dummy section from French
262                     if (sectionText.startsWith("\n=== {{S|étymologie}} ===\n: {{ébauche-étym")) {
263                         int dummy_end = sectionText.indexOf("}}", 41) + 2;
264                         while (dummy_end + 1 < sectionText.length() &&
265                                 sectionText.charAt(dummy_end) == '\n' &&
266                                 sectionText.charAt(dummy_end + 1) == '\n') ++dummy_end;
267                         sectionText = sectionText.substring(dummy_end);
268                     }
269                     if (heading.indexOf("Japanese") == -1) sectionText += translingual;
270                     final Section section = new Section(title, heading, sectionText);
271
272                     try {
273                         selector.out.writeUTF(section.title);
274                         selector.out.writeUTF(section.heading);
275                         final byte[] bytes = section.text.getBytes("UTF8");
276                         selector.out.writeInt(bytes.length);
277                         selector.out.write(bytes);
278                     } catch (IOException e) {
279                         throw new RuntimeException(e);
280                     }
281
282                     start = end;
283                     break;
284                 }
285             }
286         }
287
288     }
289
290     // -----------------------------------------------------------------------
291
292     static class Section implements java.io.Serializable {
293         private static final long serialVersionUID = -7676549898325856822L;
294
295         final String title;
296         final String heading;
297         final String text;
298
299         public Section(final String title, final String heading, final String text) {
300             this.title = title;
301             this.heading = heading;
302             this.text = text;
303
304             //System.out.printf("TITLE:%s\nHEADING:%s\nTEXT:%s\n\n\n\n\n\n", title, heading, text);
305         }
306     }
307
308     static class Selector {
309         final String outFilename;
310         final Matcher pattern;
311
312         DataOutputStream out;
313
314         public Selector(final String filename, final String pattern) {
315             this.outFilename = filename;
316             this.pattern = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE).matcher("");
317         }
318     }
319
320     // -----------------------------------------------------------------------
321
322     @Override
323     public void startElement(String uri, String localName, String qName,
324                              Attributes attributes) {
325         currentBuilder = null;
326         if ("page".equals(qName)) {
327             titleBuilder = new StringBuilder();
328
329             // Start with "\n" to better match certain strings.
330             textBuilder = new StringBuilder("\n");
331         } else if ("title".equals(qName)) {
332             currentBuilder = titleBuilder;
333         } else if ("text".equals(qName)) {
334             currentBuilder = textBuilder;
335         }
336     }
337
338     @Override
339     public void characters(char[] ch, int start, int length) throws SAXException {
340         if (currentBuilder != null) {
341             currentBuilder.append(ch, start, length);
342         }
343     }
344
345     @Override
346     public void endElement(String uri, String localName, String qName)
347     throws SAXException {
348         currentBuilder = null;
349         if ("page".equals(qName)) {
350             endPage();
351         }
352     }
353
354     public void parse(final File file) throws ParserConfigurationException,
355         SAXException, IOException {
356         final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
357         parser.parse(file, this);
358     }
359
360 }