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