]> gitweb.fperrin.net Git - DictionaryPC.git/blob - src/com/hughes/android/dictionary/engine/WiktionarySplitter.java
a0c04c5ea22851964a8377da8884562a0a6513b9
[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   static final Pattern headingStart = Pattern.compile("^(=+)[^=].*$", Pattern.MULTILINE);
43   
44   final Map<String,List<Selector>> pathToSelectors = new LinkedHashMap<String, List<Selector>>();
45   List<Selector> currentSelectors = null;
46   
47   StringBuilder titleBuilder;
48   StringBuilder textBuilder;
49   StringBuilder currentBuilder = null;
50
51   public static void main(final String[] args) throws Exception {
52     final WiktionarySplitter wiktionarySplitter = new WiktionarySplitter();
53     wiktionarySplitter.go();
54   }
55   
56   private WiktionarySplitter() {
57     List<Selector> selectors;
58     for (final String code : WiktionaryLangs.wikiCodeToIsoCodeToWikiName.keySet()) {
59       //if (code.equals("en") || code.equals("de") || code.equals("fr")) {continue;}
60       selectors = new ArrayList<WiktionarySplitter.Selector>();
61       pathToSelectors.put(String.format("data/inputs/%swiktionary-pages-articles.xml", code), selectors);
62       for (final Map.Entry<String, String> entry : WiktionaryLangs.wikiCodeToIsoCodeToWikiName.get(code).entrySet()) {
63         final String dir = String.format("data/inputs/wikiSplit/%s", code);
64         new File(dir).mkdirs();
65         selectors.add(new Selector(String.format("%s/%s.data", dir, entry.getKey()), entry.getValue()));
66       }
67     }
68   }
69
70   private void go() throws Exception {
71     final SAXParser parser = SAXParserFactoryImpl.newInstance().newSAXParser();
72
73     // Configure things.
74     for (final Map.Entry<String, List<Selector>> pathToSelectorsEntry : pathToSelectors.entrySet()) {
75       
76       currentSelectors = pathToSelectorsEntry.getValue();
77       
78       for (final Selector selector : currentSelectors) {
79         selector.out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(selector.outFilename)));
80       }
81   
82       // Do it.
83       try {
84         parser.parse(new File(pathToSelectorsEntry.getKey()), this);
85       } catch (Exception e) {
86         System.err.println("Exception during parse, lastPageTitle=" + lastPageTitle + ", titleBuilder=" + titleBuilder.toString());
87         throw e;
88       }
89       
90       // Shutdown.
91       for (final Selector selector : currentSelectors) {
92         selector.out.close();
93       }
94       
95     }
96   }
97
98   String lastPageTitle = null;
99   int pageCount = 0;
100   private void endPage() {
101     final String title = titleBuilder.toString();
102     lastPageTitle = title;
103     if (++pageCount % 1000 == 0) {
104       System.out.println("endPage: " + title + ", count=" + pageCount);
105     }
106     if (title.startsWith("Wiktionary:") || 
107             title.startsWith("Appendix:") || 
108             title.startsWith("Help:") ||
109             title.startsWith("Index:") ||
110             title.startsWith("MediaWiki:") || 
111             title.startsWith("Citations:") || 
112             title.startsWith("Concordance:") || 
113             title.startsWith("Glossary:") || 
114             title.startsWith("Rhymes:") || 
115             title.startsWith("Category:") || 
116             title.startsWith("Wikisaurus:") || 
117             title.startsWith("Unsupported titles/") || 
118             title.startsWith("Transwiki:") || 
119             title.startsWith("File:") || 
120             title.startsWith("Thread:") || 
121             title.startsWith("Template:") ||
122             title.startsWith("Summary:") ||
123             // DE
124             title.startsWith("Datei:") ||
125             title.startsWith("Verzeichnis:") ||
126             title.startsWith("Vorlage:") ||
127             title.startsWith("Thesaurus:") ||
128             title.startsWith("Kategorie:") ||
129             title.startsWith("Hilfe:") ||
130             // FR:
131             title.startsWith("Annexe:") ||
132             title.startsWith("Catégori:") ||
133             title.startsWith("Modèle:") ||
134             title.startsWith("Thésaurus:") ||
135             title.startsWith("Projet:") ||
136             title.startsWith("Aide:") ||
137             title.startsWith("Fichier:") ||
138             title.startsWith("Wiktionnaire:") ||
139             title.startsWith("Catégorie:") ||
140             title.startsWith("Portail:") ||
141             title.startsWith("utiliusateur:") ||
142             title.startsWith("Kategorio:") ||
143             // IT
144             title.startsWith("Wikizionario:") ||
145             title.startsWith("Appendice:") ||
146             title.startsWith("Categoria:") ||
147             title.startsWith("Aiuto:") ||
148             title.startsWith("Portail:") ||
149
150             // sentinel
151             false
152             ) {
153         return;
154     }
155     if (title.contains(":")) {
156         if (!title.startsWith("Sign gloss:")) {
157             System.err.println("title with colon: " + title);
158         }
159     }
160     
161     String text = textBuilder.toString();
162     
163     while (text.length() > 0) {
164       // Find start.
165       final Matcher startMatcher = headingStart.matcher(text);
166       if (!startMatcher.find()) {
167         return;
168       }
169       text = text.substring(startMatcher.end());
170       
171       final String heading = startMatcher.group();
172       for (final Selector selector : currentSelectors) {
173         if (selector.pattern.matcher(heading).find()) {
174           
175           // Find end.
176           final int depth = startMatcher.group(1).length();
177           final Pattern endPattern = Pattern.compile(String.format("^={1,%d}[^=].*$", depth), Pattern.MULTILINE);
178           
179           final Matcher endMatcher = endPattern.matcher(text);
180           final int end;
181           if (endMatcher.find()) {
182             end = endMatcher.start();
183           } else {
184             end = text.length();
185           }
186           
187           final String sectionText = text.substring(0, end);
188           final Section section = new Section(title, heading, sectionText);
189           
190           try {
191             selector.out.writeUTF(section.title);
192             selector.out.writeUTF(section.heading);
193             final byte[] bytes = section.text.getBytes("UTF8");
194             selector.out.writeInt(bytes.length);
195             selector.out.write(bytes);
196           } catch (IOException e) {
197             throw new RuntimeException(e);
198           }
199           
200           text = text.substring(end);
201         }
202       }
203     }
204     
205   }
206
207   // -----------------------------------------------------------------------
208
209   static class Section implements java.io.Serializable {
210     private static final long serialVersionUID = -7676549898325856822L;
211
212     final String title;
213     final String heading;
214     final String text;
215     
216     public Section(final String title, final String heading, final String text) {
217       this.title = title;
218       this.heading = heading;
219       this.text = text;
220       
221       //System.out.printf("TITLE:%s\nHEADING:%s\nTEXT:%s\n\n\n\n\n\n", title, heading, text);
222     }
223   }
224   
225   static class Selector {
226     final String outFilename;
227     final Pattern pattern;
228
229     DataOutputStream out;
230
231     public Selector(final String filename, final String pattern) {
232       this.outFilename = filename;
233       this.pattern = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
234     }
235   }
236
237   // -----------------------------------------------------------------------
238   
239     @Override
240     public void startElement(String uri, String localName, String qName,
241         Attributes attributes) {
242       currentBuilder = null;
243       if ("page".equals(qName)) {
244         titleBuilder = new StringBuilder();
245         
246         // Start with "\n" to better match certain strings.
247         textBuilder = new StringBuilder("\n");
248       } else if ("title".equals(qName)) {
249         currentBuilder = titleBuilder;
250       } else if ("text".equals(qName)) {
251         currentBuilder = textBuilder;
252       }
253     }
254
255     @Override
256     public void characters(char[] ch, int start, int length) throws SAXException {
257       if (currentBuilder != null) {
258         currentBuilder.append(ch, start, length);
259       }
260     }
261
262     @Override
263     public void endElement(String uri, String localName, String qName)
264         throws SAXException {
265       currentBuilder = null;
266       if ("page".equals(qName)) {
267         endPage();
268       }
269     }
270     
271
272     public void parse(final File file) throws ParserConfigurationException,
273         SAXException, IOException {
274       final SAXParser parser = SAXParserFactoryImpl.newInstance().newSAXParser();
275       parser.parse(file, this);
276     }
277
278     
279     
280 }