]> gitweb.fperrin.net Git - DictionaryPC.git/blob - src/com/hughes/android/dictionary/engine/WiktionarySplitter.java
Rename enwiktionary package to wiktionary.
[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 import javax.xml.parsers.SAXParserFactory;
32
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 SAXException, IOException, ParserConfigurationException {
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("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 ParserConfigurationException, SAXException, IOException {
71     final SAXParser parser = SAXParserFactory.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       parser.parse(new File(pathToSelectorsEntry.getKey()), this);
84       
85       // Shutdown.
86       for (final Selector selector : currentSelectors) {
87         selector.out.close();
88       }
89       
90     }
91   }
92
93   int pageCount = 0;
94   private void endPage() {
95     final String title = titleBuilder.toString();
96     if (++pageCount % 1000 == 0) {
97       System.out.println("endPage: " + title + ", count=" + pageCount);
98     }
99     
100     String text = textBuilder.toString();
101     
102     while (text.length() > 0) {
103       // Find start.
104       final Matcher startMatcher = headingStart.matcher(text);
105       if (!startMatcher.find()) {
106         return;
107       }
108       text = text.substring(startMatcher.end());
109       
110       final String heading = startMatcher.group();
111       for (final Selector selector : currentSelectors) {
112         if (selector.pattern.matcher(heading).find()) {
113           
114           // Find end.
115           final int depth = startMatcher.group(1).length();
116           final Pattern endPattern = Pattern.compile(String.format("^={1,%d}[^=].*$", depth), Pattern.MULTILINE);
117           
118           final Matcher endMatcher = endPattern.matcher(text);
119           final int end;
120           if (endMatcher.find()) {
121             end = endMatcher.start();
122           } else {
123             end = text.length();
124           }
125           
126           final String sectionText = text.substring(0, end);
127           final Section section = new Section(title, heading, sectionText);
128           
129           try {
130             selector.out.writeUTF(section.title);
131             selector.out.writeUTF(section.heading);
132             final byte[] bytes = section.text.getBytes("UTF8");
133             selector.out.writeInt(bytes.length);
134             selector.out.write(bytes);
135           } catch (IOException e) {
136             throw new RuntimeException(e);
137           }
138           
139           text = text.substring(end);
140         }
141       }
142     }
143     
144   }
145
146   // -----------------------------------------------------------------------
147
148   static class Section implements java.io.Serializable {
149     private static final long serialVersionUID = -7676549898325856822L;
150
151     final String title;
152     final String heading;
153     final String text;
154     
155     public Section(final String title, final String heading, final String text) {
156       this.title = title;
157       this.heading = heading;
158       this.text = text;
159       
160       //System.out.printf("TITLE:%s\nHEADING:%s\nTEXT:%s\n\n\n\n\n\n", title, heading, text);
161     }
162   }
163   
164   static class Selector {
165     final String outFilename;
166     final Pattern pattern;
167
168     DataOutputStream out;
169
170     public Selector(final String filename, final String pattern) {
171       this.outFilename = filename;
172       this.pattern = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
173     }
174   }
175
176   // -----------------------------------------------------------------------
177   
178     @Override
179     public void startElement(String uri, String localName, String qName,
180         Attributes attributes) {
181       currentBuilder = null;
182       if ("page".equals(qName)) {
183         titleBuilder = new StringBuilder();
184         
185         // Start with "\n" to better match certain strings.
186         textBuilder = new StringBuilder("\n");
187       } else if ("title".equals(qName)) {
188         currentBuilder = titleBuilder;
189       } else if ("text".equals(qName)) {
190         currentBuilder = textBuilder;
191       }
192     }
193
194     @Override
195     public void characters(char[] ch, int start, int length) throws SAXException {
196       if (currentBuilder != null) {
197         currentBuilder.append(ch, start, length);
198       }
199     }
200
201     @Override
202     public void endElement(String uri, String localName, String qName)
203         throws SAXException {
204       currentBuilder = null;
205       if ("page".equals(qName)) {
206         endPage();
207       }
208     }
209     
210
211     public void parse(final File file) throws ParserConfigurationException,
212         SAXException, IOException {
213       final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
214       parser.parse(file, this);
215     }
216
217     
218     
219 }