summaryrefslogtreecommitdiffabout
path: root/bin/wikitrans
blob: 01c3f9c2bfbe8b9498492159852305a02e32b2ea (plain)
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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2008-2018 Sergey Poznyakoff
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from __future__ import print_function
from __future__ import unicode_literals
import sys
import re
import tempfile
import xml.etree.ElementTree as etree
from optparse import OptionParser
try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO
from wikitrans.wiki2html  import HtmlWikiMarkup, HtmlWiktionaryMarkup
from wikitrans.wiki2text  import TextWikiMarkup, TextWiktionaryMarkup
from wikitrans.wiki2texi  import TexiWikiMarkup
from wikitrans.wikimarkup import WikiMarkup
from wikitrans.wikidump   import DumpWikiMarkup

# Set utf-8 as the default encoding for Python 2.7.
# Trying to do so using encode('utf_8')/unicode, which is
# supposed to be the right way, does not work in Python 2.7
# Simply calling sys.setdefaultencoding is not possible,
# because, for some obscure reason, Python chooses to delete
# this symbol from the namespace after setting its default
# encoding in site.py. That's why reload is needed.
try:
    reload(sys)
    sys.setdefaultencoding('utf-8')
except:
    pass

handlers = {
    'dump': {
        'default': DumpWikiMarkup,
        'wiktionary': DumpWikiMarkup
    },
    'html': {
        'default': HtmlWikiMarkup,
        'wiktionary': HtmlWiktionaryMarkup
    },
    'text': {
        'default': TextWikiMarkup,
        'wiktionary': TextWiktionaryMarkup
    },
    'texi': {
        'default': TexiWikiMarkup,
        'wiktionary': TextWikiMarkup
    }
}

def setkw(option, opt, value, parser):
    if not parser.values.kwdict:
        parser.values.kwdict = {}
    (kw,sep,val) = value.partition('=')
    if val:
        parser.values.kwdict[kw] = val

def setdebug(option, opt, value, parser):
    if not parser.values.kwdict:
        parser.values.kwdict = {}
    parser.values.kwdict['debug_level'] = value

def getwiki(url, options):
    tmp = tempfile.NamedTemporaryFile()
    if sys.version_info[0] > 2:
        import urllib.request
        with urllib.request.urlopen(url) as u:
            root = etree.fromstring(u.read())
    else:
        import urllib
        urllib.urlretrieve(url, tmp.name)
        root = etree.parse(tmp.name).getroot()
    ns = { 'wiki':'' }
    if 'version' in root.attrib:
        ns['wiki'] = 'http://www.mediawiki.org/xml/export-%s/' % root.attrib['version']
        text = root.find('wiki:page/wiki:revision/wiki:text',ns)
    if text is None:
        print("no page/revision/text element in the downloaded page")
        exit(0)

    m = re.match('(?P<url>(?:.+://)(?P<lang>.+?)\.(?P<root>wik(?:ipedia|tionary))\.org)', url)
    if m:
        options.lang = m.group('lang')
        options.kwdict['html_base'] = m.group('url') + '/wiki/'
        if m.group('root') == 'wiktionary':
            options.itype = 'wiktionary'

    options.kwdict['text'] = text.text.encode()

def main():
    usage = '%prog [OPTIONS] ARG'
    version = '%prog 1.3'
    description = """Translates MediaWiki documents markup to various other formats.
If ARG looks like a URL, the wiki text to be converted will be downloaded
from that URL.
Otherwise, if --base-url is given, ARG is treated as the name of the page to
get from the WikiMedia istallation at that URL.
Otherwise, ARG is name of the file to read wiki material from.
"""
    epilog = "Report bugs to: <gray+wikitrans@gnu.org.ua>"

    parser = OptionParser(usage=usage,
                          version=version,
                          description=description,
                          epilog=epilog)
    parser.add_option('-v', '--verbose',
                      action="count", dest="verbose",
                      help="verbose operation")
    parser.add_option('-I', '--input-type',
                      action='store', type='string', dest='itype',
                      default='default',
                      help='set input document type ("default" or "wiktionary")')
    parser.add_option('-t', '--to', '--type',
                      action='store', type='string', dest='otype',
                      default='html',
                      help='set output document type ("html" (default), "texi" or "text")')
    parser.add_option('-l', '--lang',
                      action='store', type='string', dest='lang',
                      default='en',
                      help='set input document language')
    parser.add_option('-o', '--option',
                      action='callback', callback=setkw,
                      type='string', dest='kwdict',
                      default={},
                      help='set keyword option for the parser class constructor')
    parser.add_option('-d', '--debug',
                      action='callback', callback=setdebug,
                      type='int', dest='kwdict',
                      help='set debug level (0..100)')
    parser.add_option('-D', '--dump',
                      action='store_const', const='dump',
                      dest='otype',
                      help='dump parse tree and exit; similar to --type=dump')
    parser.add_option('-b', '--base-url',
                      action='store', type='string', dest='base_url',
                      help='set base url')


    (options, args) = parser.parse_args()
    if len(args) == 1:
        if options.base_url:
            getwiki(options.base_url + '/wiki/Special:Export/' + args[0],
                    options)
        elif args[0] == '-':
            options.kwdict['file'] = sys.stdin
        elif re.match('^(http|ftp)s?://',args[0]):
            getwiki(args[0], options)
        else:
            options.kwdict['filename'] = args[0]
    else:
        parser.error("bad number of arguments")

    options.kwdict['lang'] = options.lang # FIXME

    if options.otype == 'dump' and not 'indent' in options.kwdict:
        options.kwdict['indent'] = 2
    if options.otype in handlers:
        if options.itype in handlers[options.otype]:
            markup = handlers[options.otype][options.itype](**options.kwdict)
            markup.parse()
            print("%s" % str(markup))
            exit(0)
        else:
            print("input type %s is not supported for %s output" % (options.itype, options.otype))
    else:
        print("unsupported output type: %s" % options.otype)
    exit(1)

if __name__ == '__main__':
    main()

Return to:

Send suggestions and report system problems to the System administrator.