Debian Codegraph @

python/examples/liblouisxslt.py

raw symbols SCIP
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
17 from optparse import OptionParser
18
19 import libxml2
20 import libxslt
21 import louis
22
23 nodeName = None
24
25 emphasisMap = {
26 "plain_text": louis.plain_text,
27 "italic": louis.italic,
28 "underline": louis.underline,
29 "bold": louis.bold,
30 "computer_braille": louis.computer_braille,
31 }
32
33
34 def translate(ctx, str, translation_table, emphasis=None):
35 global nodeName
36
37 try:
38 pctxt = libxslt.xpathParserContext(_obj=ctx)
39 ctxt = pctxt.context()
40 tctxt = ctxt.transformContext()
41 nodeName = tctxt.insertNode().name
42 except:
43 pass
44
45 typeform = len(str) * [emphasisMap[emphasis]] if emphasis else None
46 braille = louis.translate(
47 [translation_table], str.decode("utf-8"), typeform=typeform
48 )[0]
49 return braille.encode("utf-8")
50
51
52 def xsltProcess(styleFile, inputFile, outputFile):
53 """Transform an xml inputFile to an outputFile using the given styleFile"""
54 styledoc = libxml2.parseFile(styleFile)
55 style = libxslt.parseStylesheetDoc(styledoc)
56 doc = libxml2.parseFile(inputFile)
57 result = style.applyStylesheet(doc, None)
58 style.saveResultToFilename(outputFile, result, 0)
59 style.freeStylesheet()
60 doc.freeDoc()
61 result.freeDoc()
62
63
64 libxslt.registerExtModuleFunction(
65 "translate", "http://liblouis.org/liblouis", translate
66 )
67
68
69 def main():
70 usage = "Usage: %prog [options] styleFile inputFile outputFile"
71 parser = OptionParser(usage)
72 (options, args) = parser.parse_args()
73 if len(args) != 3:
74 parser.error("incorrect number of arguments")
75 xsltProcess(args[0], args[1], args[2])
76
77
78 if __name__ == "__main__":
79 main()