blob: 0c0382eede5ea721bda3113cbacbe8d5c8cba8e1 [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
Christian Eglic0165162010-01-15 14:55:27 +000011import sys
12import getopt
13from optparse import OptionParser
14
Christian Eglic0165162010-01-15 14:55:27 +000015nodeName = None
16
Christian Egli554fb832010-02-03 09:54:49 +000017emphasisMap = {
Christian Eglic0165162010-01-15 14:55:27 +000018 'plain_text' : louis.plain_text,
19 'italic' : louis.italic,
20 'underline' : louis.underline,
21 'bold' : louis.bold,
22 'computer_braille' : louis.computer_braille}
23
Christian Egli554fb832010-02-03 09:54:49 +000024def translate(ctx, str, translation_table, emphasis=None):
Christian Eglic0165162010-01-15 14:55:27 +000025 global nodeName
26
27 try:
28 pctxt = libxslt.xpathParserContext(_obj=ctx)
29 ctxt = pctxt.context()
30 tctxt = ctxt.transformContext()
31 nodeName = tctxt.insertNode().name
32 except:
33 pass
Christian Egli554fb832010-02-03 09:54:49 +000034
35 typeform = len(str)*[emphasisMap[emphasis]] if emphasis else None
Christian Eglic0165162010-01-15 14:55:27 +000036 braille = louis.translate([translation_table], str.decode('utf-8'), typeform=typeform)[0]
Christian Eglibd308342010-01-19 14:05:34 +000037 return braille.encode('utf-8')
Christian Eglic0165162010-01-15 14:55:27 +000038
39def xsltProcess(styleFile, inputFile, outputFile):
40 """Transform an xml inputFile to an outputFile using the given styleFile"""
41 styledoc = libxml2.parseFile(styleFile)
42 style = libxslt.parseStylesheetDoc(styledoc)
43 doc = libxml2.parseFile(inputFile)
44 result = style.applyStylesheet(doc, None)
45 style.saveResultToFilename(outputFile, result, 0)
46 style.freeStylesheet()
47 doc.freeDoc()
48 result.freeDoc()
49
50libxslt.registerExtModuleFunction("translate", "http://liblouis.org/liblouis", translate)
51
52def main():
53 usage = "Usage: %prog [options] styleFile inputFile outputFile"
54 parser = OptionParser(usage)
55 (options, args) = parser.parse_args()
56 if len(args) != 3:
57 parser.error("incorrect number of arguments")
58 xsltProcess(args[0], args[1], args[2])
59
60if __name__ == "__main__":
61 main()