forked from wikireader/wikireader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ArticleParser.py
executable file
·204 lines (167 loc) · 6.99 KB
/
ArticleParser.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# COPYRIGHT: Openmoko Inc. 2009
# LICENSE: GPL Version 3 or later
# DESCRIPTION: Article Parser
# AUTHORS: Sean Moss-Pultz <sean@openmoko.com>
# Christopher Hall <hsw@openmoko.com>
import os, sys, re, subprocess
import getopt
import os.path
import sqlite3
from types import *
verbose = False
PARSER_COMMAND = '(cd mediawiki-offline && php wr_parser.php -)'
# Regular expressions for parsing the XML
subs = [
(re.compile(r'\s*(==\s*External\s+links\s*==.*)$', re.IGNORECASE + re.DOTALL), ''),
(re.compile(r'\s*(<|<)gallery(>|>).*?(<|<)/gallery(>|>)', re.IGNORECASE + re.DOTALL), ''),
(re.compile(r'((<|<)ref\s+name.*?/(>|>))', re.IGNORECASE), ''),
(re.compile(r'((<|<)!--.*?--(>|>)|(<|<)ref.*?(<|<)/ref(>|>))', re.IGNORECASE + re.DOTALL), ''),
(re.compile(r'(<|<)br\s+/(>|>)', re.IGNORECASE), '\n'),
(re.compile(r'\[\[(file|image):.*$', re.IGNORECASE + re.MULTILINE), ''),
(re.compile(r'\[\[\w\w:(\[\[[^\]\[]*\]\]|[^\]\[])*\]\]', re.IGNORECASE), ''),
# Wikipedia's installed Parser extension tags
# <categorytree>, <charinsert>, <hiero>, <imagemap>, <inputbox>, <poem>,
# <pre>, <ref>, <references>, <source>, <syntaxhighlight> and <timeline>
# All referenced using special characters
# Ex: <timeline> --> <timeline>
# For now, we're only going to remove <timeline>
(re.compile(r'\s*(<|<)timeline(>|>).*?(<|<)/timeline(>|>)', re.IGNORECASE + re.DOTALL), ''),
(re.compile(r'\s*(<|<)imagemap(>|>).*?(<|<)/imagemap(>|>)', re.IGNORECASE + re.DOTALL), ''),
(re.compile(r'(<|<).*?(>|>)', re.IGNORECASE), ''),
(re.compile(r'&([a-zA-Z]{2,8});', re.IGNORECASE), r'&\1;')
# change % so php: wr_parser does not convert them
(re.compile(r'%', re.IGNORECASE), r'%25')
]
def usage(message):
if None != message:
print 'error:', message
print 'usage: %s <options> {xml-file...}' % os.path.basename(__file__)
print ' --help This message'
print ' --verbose Enable verbose output'
print ' --xhtml=file XHTML output [all_articles.html]'
print ' --start=n First artcle to process [1] (1k => 1000)'
print ' --count=n Number of artcles to process [all] (1k => 1000)'
print ' --article-offsets=file Article file offsets database input [offsets.db]'
print ' --just-cat Replace php parser be "cat" for debugging'
print ' --no-output Do not run any parsing'
exit(1)
def main():
global verbose
global PARSER_COMMAND
global total_articles
try:
opts, args = getopt.getopt(sys.argv[1:], 'hvx:s:c:o:jn',
['help', 'verbose', 'xhtml=',
'start=', 'count=',
'article-offsets=',
'just-cat',
'no-output',
])
except getopt.GetoptError, err:
usage(err)
verbose = False
out_name = 'all_articles.html'
off_name = 'offsets.db'
start_article = 1
article_count = 'all'
do_output = True
for opt, arg in opts:
if opt in ('-v', '--verbose'):
verbose = True
elif opt in ('-h', '--help'):
usage(None)
elif opt in ('-x', '--xhtml'):
out_name = arg
elif opt in ('-o', '--article-offsets'):
off_name = arg
elif opt in ('-j', '--just-cat'):
PARSER_COMMAND = 'cat'
elif opt in ('-n', '--no-output'):
do_output = False
elif opt in ('-s', '--start'):
if arg[-1] == 'k':
arg = arg[:-1] + '000'
try:
start_article = int(arg)
except ValueError:
usage('%s=%s" is not numeric' % (opt, arg))
if start_article < 1:
usage('%s=%s" must be >= 1' % (opt, arg))
elif opt in ('-c', '--count'):
if arg[-1] == 'k':
arg = arg[:-1] + '000'
if arg != 'all':
try:
article_count = int(arg)
except ValueError:
usage('%s=%s" is not numeric' % (opt, arg))
if article_count <= 0:
usage('%s=%s" must be > zero' % (opt, arg))
else:
usage('unhandled option: ' + opt)
offset_db = sqlite3.connect(off_name)
offset_db.execute('pragma synchronous = 0')
offset_db.execute('pragma temp_store = 2')
#offset_db.execute('pragma locking_mode = exclusive') # Sean: Ask Chris if this is ok?!
offset_db.execute('pragma read_uncommitted = true')
offset_db.execute('pragma cache_size = 20000000')
offset_db.execute('pragma default_cache_size = 20000000')
#offset_db.execute('pragma journal_mode = memory')
offset_db.execute('pragma journal_mode = off')
offset_cursor = offset_db.cursor()
if do_output:
newf = subprocess.Popen(PARSER_COMMAND + ' > ' + out_name, shell=True, stdin=subprocess.PIPE).stdin
else:
newf = None
# process all required articles
current_file_id = None
f = None
total_articles = 0
while article_count == 'all' or article_count != 0:
offset_cursor.execute('select file_id, title, seek, length from offsets where article_number = ? limit 1',
(start_article,))
row = offset_cursor.fetchone()
if None == row:
break
(title, file_id, seek, length) = row # this order is different from select!
#print "row : ", row # just to show select order is wrong, check create table and insert/import
if file_id != current_file_id:
current_file_id = file_id
if f:
f.close()
offset_cursor.execute('select filename from files where file_id = ? limit 1', (file_id,))
filename = offset_cursor.fetchone()[0]
f = open(filename, 'r')
if verbose:
print 'Open:', filename
f.seek(seek)
process_article_text(title.encode('utf-8'), f.read(length), newf)
if article_count != 'all':
article_count -= 1
total_articles += 1
start_article += 1
if not verbose and total_articles % 1000 == 0:
print 'Count: %d' % total_articles
# close files
if f:
f.close()
if newf:
newf.close()
print 'Total: %d' % total_articles
def process_article_text(title, text, newf):
global verbose
global subs
if verbose:
print "[PA] " + title
for e,r in subs:
text = e.sub(r, text)
if newf:
newf.write(title[1:]); # We pad the title to force the database to import strings
newf.write('\n__NOTOC__\n')
newf.write(text + '\n')
newf.write('***EOF***\n')
# run the program
if __name__ == "__main__":
main()