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