forked from mithro/media2iki
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmediawiki2markdown.py
executable file
·563 lines (453 loc) · 14 KB
/
mediawiki2markdown.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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
#!/usr/bin/python
#
# -*- coding: utf-8 -*-
# vim: set ts=2 sw=2 et sts=2 ai:
"""This program converts mediawiki format to markdown.
It takes a file as an argument and outputs the markdown text to stdout.
"""
# stdlib imports
import cStringIO as StringIO
import optparse
import sys
# External module imports
from mwlib.uparser import simpleparse
from mwlib.parser import nodes
class options:
# Should we drop to the debugger on error
DEBUGGER = False
# Should we die on unknown flags
STRICT = True
parser = optparse.OptionParser()
parser.add_option(
"-f", "--file", dest="file",
help="wikimedia FILE to read.", metavar="FILE")
parser.add_option(
"-d", "--debugger", dest="DEBUGGER", action="store_true",
default=sys.stdout.isatty() and sys.stdin.isatty(),
help="Drop to Python PDB debugger on an error.")
parser.add_option(
"--no-debugger", dest="DEBUGGER", action="store_false",
default=sys.stdout.isatty() and sys.stdin.isatty(),
help="Don't drop to Python PDB debugger on an error.")
parser.add_option(
"-s", "--strict", dest="STRICT", action="store_true", default=options.STRICT,
help="Error on known tags, style or other problems.")
parser.add_option(
"--no-strict", dest="STRICT", action="store_false", default=options.STRICT,
help="Error on known tags, style or other problems.")
parser.add_option(
"-l", "--lenient", dest="STRICT", action="store_true", default=options.STRICT,
help="Don't error on known tags, style or other problems.")
def debugger():
if options.DEBUGGER:
# Flush the output to make sure we see the latest errors/output
sys.stderr.write('\n\n')
sys.stderr.flush()
sys.stdout.write('\n\n')
sys.stdout.flush()
import traceback, pdb
type, value, tb = sys.exc_info()
pdb.post_mortem(tb)
else:
raise
class BaseConverter(object):
def __init__(self):
self.out = ""
self.listmode = []
def append(self, s):
if isinstance(s, unicode):
s = s.encode('utf-8')
self.out += s
def getvalue(self):
out = self.out
self.out = ""
return out
def parse_node(self, node):
try:
tagname = 'on_'+str(node.tagname).replace('@', '')
classname = 'on_'+node.__class__.__name__.lower().replace('@', '')
f = getattr(self, tagname, getattr(self, classname, None))
f(node)
except AttributeError, e:
sys.stderr.write('Unknown node: '+(node.tagname or node.__class__.__name__.lower()))
assert not options.STRICT
def parse_children(self, node):
for child in node.children:
self.parse_node(child)
on_node = parse_children
def on_article(self, node):
self.parse_children(node)
self.produce_dls()
def on_ol(self, node):
self.listmode.append('order')
self.append('\n')
self.parse_children(node)
self.listmode.pop(-1)
def on_ul(self, node):
self.listmode.append('unorder')
self.append('\n')
self.parse_children(node)
self.listmode.pop(-1)
def on_text(self, node):
self.append(node.asText())
def on_style(self, node):
# Definition list?
if node.caption == ';':
if not hasattr(self, 'dls'):
self.dls = []
self.dls.append(node)
elif node.caption == ':':
# If not part of an definition list, it's an indent...
if not hasattr(self, 'dls'):
self.on_blockquote(node)
else:
self.dls.append(node)
# italics
elif node.caption == "'''":
self.on_bold(node)
# bold
elif node.caption == "''":
self.on_italics(node)
# underline
elif node.caption == "u":
self.on_underline(node)
else:
sys.stderr.write("Unknown style: %s\n" % node.caption)
assert not options.STRICT
def on_underline(self, node):
self.append("<u>")
self.parse_children(node)
self.append("</u>")
# Ignore category links as we don't have anything similar
def on_categorylink(self, node):
return
def on_table(self, node):
table_cell_parser = self.__class__()
table = []
table_caption = ""
table_width = 0
table_column_widths = []
for row in node.children:
if isinstance(row, nodes.Caption):
table_cell_parser.parse_children(row)
output = table_cell_parser.getvalue()
table_caption += output
continue
if len(row.children) > table_width:
table_width = len(row.children)
while len(table_column_widths) < table_width:
table_column_widths.append(0)
cells = []
for i, cell in enumerate(row.children):
table_cell_parser.parse_children(cell)
cell_data = table_cell_parser.getvalue()
if table_column_widths[i] < len(cell_data):
table_column_widths[i] = len(cell_data)
cells.append({'node': cell, 'rendered': cell_data})
args = {'rowtype': row}
if len(row.children):
args['celltype'] = row.children[-1]
if len(cells):
args['cells'] = cells
table.append(args)
for row in table:
while len(row['cells']) < table_width:
row['cells'].append({'rendered': ''})
self.on_process_table(table_caption, table_column_widths, table)
class HTMLConverter(BaseConverter):
"""During HTML output (such as dl lists and tables) Markdown doesn't work."""
def on_p(self, node):
self.append("<p>")
self.parse_children(node)
self.append("</p>")
self.produce_dls()
def on_italics(self, node):
self.append("<em>")
self.parse_children(node)
self.append("</em>")
def on_bold(self, node):
self.append("<strong>")
self.parse_children(node)
self.append("</strong>")
def on_url(self, node):
parser = HTMLConverter()
parser.parse_children(node)
output = parser.getvalue()
if not output:
output = node.caption
self.append("<a href='%s'>%s</a>" % (
node.caption.replace(' ', '_'), output))
on_namedurl = on_url
def on_imagelink(self, node):
self.append("<img src='%s' alt='%s' />'" % (
node.target.replace('Image:', '').replace(' ', '_'), node.asText()))
def on_articlelink(self, node):
for i in ['jpg', 'png', 'gif']:
if node.target.endswith(i):
self.on_imagelink(node)
break
else:
self.append("<a href='%s'>%s</a>" % (
node.caption.replace(' ', '_'), node.caption))
def on_namespacelink(self, node):
for i in ['jpg', 'png', 'gif']:
if node.target.endswith(i):
self.on_imagelink(node)
break
else:
node.caption = node.target
self.on_url(node)
def produce_dls(self):
# We need to specially handle defintion lists
if hasattr(self, "dls"):
self.append("<dl>\n")
dls = self.dls
del self.dls
for dl in dls:
if dl.caption == ';':
self.append('<dt>')
self.parse_children(dl)
self.append('</dt>\n')
elif dl.caption == ':':
self.append('<dd>')
self.parse_children(dl)
self.append('</dd>\n')
self.append("</dl>\n")
self.append('\n')
def on_section(self, node):
self.append("\n")
self.append("<h%i>" % node.level)
self.parse_node(node.children[0])
self.append("</h%i>" %node.level)
for child in node.children[1:]:
self.parse_node(child)
class MarkdownConverter(BaseConverter):
def __init__(self):
BaseConverter.__init__(self)
self.html = HTMLConverter()
def parse(self, text):
sys_stdout = sys.stdout
ast_str = StringIO.StringIO()
sys.stdout = ast_str
ast = simpleparse(text.decode('utf-8'))
sys.stdout = sys_stdout
self.parse_node(ast)
def on_blockquote(self, node):
parser = MarkdownConverter()
parser.parse_children(node)
output = parser.getvalue()
lines = []
for line in output.split('\n'):
if line:
lines.append("> "*len(node.caption)+line)
else:
lines.append(line)
self.append("\n".join(lines))
def on_preformatted(self, node):
parser = MarkdownConverter()
parser.parse_children(node)
output = parser.getvalue()
lines = []
for line in output.split('\n'):
if line:
lines.append(" "+line)
else:
lines.append(line)
self.append("\n".join(lines))
def on_pre(self, node):
parser = HTMLConverter()
parser.parse_children(node)
output = parser.getvalue()
self.append('<pre>%s</pre>\n' % output)
def on_code(self, node):
self.append('`')
self.parse_children(node)
self.append('`')
def on_tt(self, node):
self.append('<tt>')
self.parse_children(node)
self.append('</tt>')
def on_p(self, node):
self.parse_children(node)
self.produce_dls()
def produce_dls(self):
if hasattr(self, "dls"):
self.append("<dl>\n")
dls = self.dls
del self.dls
for dl in dls:
if dl.caption == ';':
self.append('<dt>')
self.html.parse_children(dl)
self.append(self.html.getvalue())
self.append('</dt>\n')
elif dl.caption == ':':
self.append('<dd>')
self.html.parse_children(dl)
self.append(self.html.getvalue())
self.append('</dd>\n')
self.append("</dl>\n")
def on_italics(self, node):
self.append("_")
self.parse_children(node)
self.append("_")
def on_bold(self, node):
self.append("**")
self.parse_children(node)
self.append("**")
def on_gallery(self, node):
"""Gallery widgets are converted to lists."""
for child in node:
self.append('* ')
self.parse_node(child)
self.append('\n')
def on_url(self, node):
parser = MarkdownConverter()
parser.parse_children(node)
output = parser.getvalue().strip()
if not output:
self.append("<%s>" % node.caption)
else:
self.append("[")
self.append(output)
self.append("](%s)" % node.caption)
on_namedurl = on_url
def on_imagelink(self, node):
self.append('![%s](%s)' % (
node.asText(), node.target.replace('Image:', '').replace(' ', '_')))
def on_articlelink(self, node):
for i in ['jpg', 'png', 'gif']:
if node.target.endswith(i):
self.on_imagelink(node)
break
else:
self.append("[%s](/%s)" % (node.target, node.target.replace(' ', '_')))
def on_namespacelink(self, node):
for i in ['jpg', 'png', 'gif']:
if node.target.endswith(i):
self.on_imagelink(node)
break
else:
node.caption = node.target.replace(' ', '_')
self.on_url(node)
def on_section(self, node):
self.append("\n")
self.append("#" * node.level + " ")
self.parse_node(node.children[0])
self.append(" "+"#" * node.level)
self.append("\n")
for child in node.children[1:]:
self.parse_node(child)
def on_li(self, node):
listmode = {'order': '1.', 'unorder': '*'}
# mediawiki format looks like the following:
# * List item A
# *: More list item A
# which mwlib converts to
# Item tagname='li'->'li'
# Node lineprefix=
# u' List item A'
# u'\n'
# Style':'
# Node
# Node lineprefix=
# Paragraph tagname='p'->'p'
# u'More list item A'
#
# So we need to strip out the Style elements
children = [node.children[0]]
for child in node.children[1:]:
if isinstance(child, nodes.Style) and child.caption == ':':
children += child.children
else:
children.append(child)
node.children = children
parser = MarkdownConverter()
parser.parse_children(node)
output = parser.getvalue()
if not output.strip():
return
# Strip a leading space (from the following)
# *> <test
if output and output[0] == ' ':
output = output[1:]
indent = ' '*(len(self.listmode)-1)
output = output.split('\n')
lines = ["%s%s %s" % (
indent, listmode[self.listmode[-1]], output[0].lstrip())]
for line in output[1:]:
if line:
lines.append("%s %s" % (indent, line.lstrip()))
else:
lines.append(line)
self.append("\n".join(lines))
def on_tagnode(self, node):
if node.caption == 'hr':
self.append('-'*75+'\n')
elif node.caption == 'br':
self.append('<br>')
else:
sys.stderr.write( "Unknown tag %s %s\n" % (node, node.caption))
assert not options.STRICT
def on_process_table(self, caption, widths, rows):
if caption:
self.append('### %s ###\n' % caption)
# Insert a dummy header if one doesn't exist
if rows[0]['celltype'].tagname != 'th':
fakenode = nodes.Node()
fakenode.tagname = 'th'
fakenode.vlist = {}
rows.insert(0, {'rowtype': rows[0]['rowtype'],
'celltype': fakenode,
'cells': [{'node': fakenode, 'rendered': ''}]*len(widths)})
header = rows[0]
for row in rows:
line = '| '
divider = '| '
for i, cell in enumerate(row['cells']):
headernode = header['cells'][i].get('node', None)
if headernode:
align = headernode.vlist.get('align', 'left')
else:
align = 'left'
width = widths[i]
rendered = unicode(cell['rendered'], 'utf-8').strip()
rendered = "<br>".join(rendered.split('\n'))
if align == 'right':
f = rendered.rjust
divider += '-'*(width-1) + ':'
elif align == 'center' or align == 'centre':
f = rendered.center
divider += ':' + '-'*(width-2) + ':'
elif align == 'left':
f = rendered.ljust
divider += '-'*width
else:
assert False, 'Unknown alignment %s (%s)' % (cell['align'], cell)
line += f(widths[i])
line += ' | '
divider += ' | '
self.append(line[:-2])
self.append('\n')
if row['celltype'].tagname == 'th':
self.append(divider[:-2])
self.append('\n')
header = row
def main(argv):
global options
(options, args) = parser.parse_args(argv)
if options.file:
infile = file(options.file)
elif args:
infile = file(args[0])
else:
infile = sys.stdin
mediawiki = infile.read()
try:
c = MarkdownConverter()
c.parse(mediawiki)
print c.out
except:
debugger()
if __name__ == "__main__":
main(sys.argv[1:])