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