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