blob: 575bb4a92e1cb9b561a8cb68b4cdbc258d886b80 [file] [log] [blame]
Christian Eglic0165162010-01-15 14:55:27 +00001#! /usr/bin/python -u
2#
3# This is a very simple example on how to extend libxslt to be able to
4# invoke liblouis from xslt. See also the accompanying
5# dtbook2brldtbook.xsl in the same directory which simpy copies a dtbook
6# xml and translates all the text node into Braille.
7
8import louis
9import libxml2
10import libxslt
11import textwrap
12import sys
13import getopt
14from optparse import OptionParser
15
16wrapper = textwrap.TextWrapper(width=80, initial_indent=' ', subsequent_indent=' ')
17
18nodeName = None
19
20modeMap = {
21 'plain_text' : louis.plain_text,
22 'italic' : louis.italic,
23 'underline' : louis.underline,
24 'bold' : louis.bold,
25 'computer_braille' : louis.computer_braille}
26
27def translate(ctx, str, translation_table, mode=None):
28 global nodeName
29
30 try:
31 pctxt = libxslt.xpathParserContext(_obj=ctx)
32 ctxt = pctxt.context()
33 tctxt = ctxt.transformContext()
34 nodeName = tctxt.insertNode().name
35 except:
36 pass
37
38 typeform = len(str)*[modeMap[mode]] if mode else None
39 braille = louis.translate([translation_table], str.decode('utf-8'), typeform=typeform)[0]
40 braille = braille.encode('utf-8')
41 return wrapper.fill(braille)
42
43def xsltProcess(styleFile, inputFile, outputFile):
44 """Transform an xml inputFile to an outputFile using the given styleFile"""
45 styledoc = libxml2.parseFile(styleFile)
46 style = libxslt.parseStylesheetDoc(styledoc)
47 doc = libxml2.parseFile(inputFile)
48 result = style.applyStylesheet(doc, None)
49 style.saveResultToFilename(outputFile, result, 0)
50 style.freeStylesheet()
51 doc.freeDoc()
52 result.freeDoc()
53
54libxslt.registerExtModuleFunction("translate", "http://liblouis.org/liblouis", translate)
55
56def main():
57 usage = "Usage: %prog [options] styleFile inputFile outputFile"
58 parser = OptionParser(usage)
59 (options, args) = parser.parse_args()
60 if len(args) != 3:
61 parser.error("incorrect number of arguments")
62 xsltProcess(args[0], args[1], args[2])
63
64if __name__ == "__main__":
65 main()