Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / third_party / liblouis / src / python / examples / liblouisxslt.py
1 #! /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
8 import louis
9 import libxml2
10 import libxslt
11 import sys
12 import getopt
13 from optparse import OptionParser
14
15 nodeName = None
16
17 emphasisMap = {
18     'plain_text' : louis.plain_text, 
19     'italic' : louis.italic, 
20     'underline' : louis.underline, 
21     'bold' : louis.bold, 
22     'computer_braille' : louis.computer_braille}
23
24 def translate(ctx, str, translation_table, emphasis=None):
25     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
34
35     typeform = len(str)*[emphasisMap[emphasis]] if emphasis else None
36     braille = louis.translate([translation_table], str.decode('utf-8'), typeform=typeform)[0]
37     return braille.encode('utf-8')
38
39 def 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
50 libxslt.registerExtModuleFunction("translate", "http://liblouis.org/liblouis", translate)
51
52 def 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
60 if __name__ == "__main__":
61     main()