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