blob: 2f1267b57c402fb053415971df7034f750709572 [file] [log] [blame]
Christian Eglic0165162010-01-15 14:55:27 +00001#! /usr/bin/python -u
2#
Christian Egli0f804f32014-09-18 12:48:18 +02003# 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
Christian Eglic0165162010-01-15 14:55:27 +000012# 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
Christian Eglic0165162010-01-15 14:55:27 +000020import sys
21import getopt
22from optparse import OptionParser
23
Christian Eglic0165162010-01-15 14:55:27 +000024nodeName = None
25
Christian Egli554fb832010-02-03 09:54:49 +000026emphasisMap = {
Christian Eglic0165162010-01-15 14:55:27 +000027 'plain_text' : louis.plain_text,
28 'italic' : louis.italic,
29 'underline' : louis.underline,
30 'bold' : louis.bold,
31 'computer_braille' : louis.computer_braille}
32
Christian Egli554fb832010-02-03 09:54:49 +000033def translate(ctx, str, translation_table, emphasis=None):
Christian Eglic0165162010-01-15 14:55:27 +000034 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
Christian Egli554fb832010-02-03 09:54:49 +000043
44 typeform = len(str)*[emphasisMap[emphasis]] if emphasis else None
Christian Eglic0165162010-01-15 14:55:27 +000045 braille = louis.translate([translation_table], str.decode('utf-8'), typeform=typeform)[0]
Christian Eglibd308342010-01-19 14:05:34 +000046 return braille.encode('utf-8')
Christian Eglic0165162010-01-15 14:55:27 +000047
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()