1#! /usr/bin/python -u
2#
3# liblouis Braille Translation and Back-Translation Library
4
5# Copyright (C) 2010 Swiss Library for the Blind, Visually Impaired and Print Disabled
6
7# Copying and distribution of this file, with or without modification,
8# are permitted in any medium without royalty provided the copyright
9# notice and this notice are preserved. This file is offered as-is,
10# without any warranty.
11
12# This is a very simple example on how to extend libxslt to be able to
13# invoke liblouis from xslt. See also the accompanying
14# dtbook2brldtbook.xsl in the same directory which simpy copies a dtbook
15# xml and translates all the text node into Braille.
16
17import louis
18import libxml2
19import libxslt
20import sys
21import getopt
22from optparse import OptionParser
23
24nodeName = None
25
26emphasisMap = {
27    'plain_text' : louis.plain_text,
28    'italic' : louis.italic,
29    'underline' : louis.underline,
30    'bold' : louis.bold,
31    'computer_braille' : louis.computer_braille}
32
33def translate(ctx, str, translation_table, emphasis=None):
34    global nodeName
35
36    try:
37        pctxt = libxslt.xpathParserContext(_obj=ctx)
38        ctxt = pctxt.context()
39        tctxt = ctxt.transformContext()
40        nodeName = tctxt.insertNode().name
41    except:
42        pass
43
44    typeform = len(str)*[emphasisMap[emphasis]] if emphasis else None
45    braille = louis.translate([translation_table], str.decode('utf-8'), typeform=typeform)[0]
46    return braille.encode('utf-8')
47
48def xsltProcess(styleFile, inputFile, outputFile):
49    """Transform an xml inputFile to an outputFile using the given styleFile"""
50    styledoc = libxml2.parseFile(styleFile)
51    style = libxslt.parseStylesheetDoc(styledoc)
52    doc = libxml2.parseFile(inputFile)
53    result = style.applyStylesheet(doc, None)
54    style.saveResultToFilename(outputFile, result, 0)
55    style.freeStylesheet()
56    doc.freeDoc()
57    result.freeDoc()
58
59libxslt.registerExtModuleFunction("translate", "http://liblouis.org/liblouis", translate)
60
61def main():
62    usage = "Usage: %prog [options] styleFile inputFile outputFile"
63    parser = OptionParser(usage)
64    (options, args) = parser.parse_args()
65    if len(args) != 3:
66        parser.error("incorrect number of arguments")
67    xsltProcess(args[0], args[1], args[2])
68
69if __name__ == "__main__":
70    main()
71