Christian Egli | c016516 | 2010-01-15 14:55:27 +0000 | [diff] [blame^] | 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 textwrap |
| 12 | import sys |
| 13 | import getopt |
| 14 | from optparse import OptionParser |
| 15 | |
| 16 | wrapper = textwrap.TextWrapper(width=80, initial_indent=' ', subsequent_indent=' ') |
| 17 | |
| 18 | nodeName = None |
| 19 | |
| 20 | modeMap = { |
| 21 | 'plain_text' : louis.plain_text, |
| 22 | 'italic' : louis.italic, |
| 23 | 'underline' : louis.underline, |
| 24 | 'bold' : louis.bold, |
| 25 | 'computer_braille' : louis.computer_braille} |
| 26 | |
| 27 | def translate(ctx, str, translation_table, mode=None): |
| 28 | global nodeName |
| 29 | |
| 30 | try: |
| 31 | pctxt = libxslt.xpathParserContext(_obj=ctx) |
| 32 | ctxt = pctxt.context() |
| 33 | tctxt = ctxt.transformContext() |
| 34 | nodeName = tctxt.insertNode().name |
| 35 | except: |
| 36 | pass |
| 37 | |
| 38 | typeform = len(str)*[modeMap[mode]] if mode else None |
| 39 | braille = louis.translate([translation_table], str.decode('utf-8'), typeform=typeform)[0] |
| 40 | braille = braille.encode('utf-8') |
| 41 | return wrapper.fill(braille) |
| 42 | |
| 43 | def xsltProcess(styleFile, inputFile, outputFile): |
| 44 | """Transform an xml inputFile to an outputFile using the given styleFile""" |
| 45 | styledoc = libxml2.parseFile(styleFile) |
| 46 | style = libxslt.parseStylesheetDoc(styledoc) |
| 47 | doc = libxml2.parseFile(inputFile) |
| 48 | result = style.applyStylesheet(doc, None) |
| 49 | style.saveResultToFilename(outputFile, result, 0) |
| 50 | style.freeStylesheet() |
| 51 | doc.freeDoc() |
| 52 | result.freeDoc() |
| 53 | |
| 54 | libxslt.registerExtModuleFunction("translate", "http://liblouis.org/liblouis", translate) |
| 55 | |
| 56 | def main(): |
| 57 | usage = "Usage: %prog [options] styleFile inputFile outputFile" |
| 58 | parser = OptionParser(usage) |
| 59 | (options, args) = parser.parse_args() |
| 60 | if len(args) != 3: |
| 61 | parser.error("incorrect number of arguments") |
| 62 | xsltProcess(args[0], args[1], args[2]) |
| 63 | |
| 64 | if __name__ == "__main__": |
| 65 | main() |