1 # -*- coding: utf-8 -*-
4 # This file is part of LyX, the document processor.
5 # Licence details can be found in the file COPYING.
7 # \author Thibaut Cuvelier
9 # Full author contact details are available in file CREDITS
12 # python docbook2epub.py java_binary in.docbook out.epub
14 from __future__ import print_function
24 def _parse_nullable_argument(arg):
25 return arg if arg != '' and arg != 'none' else None
29 def __init__(self, args=None):
34 print('Seven arguments are expected, only %s found: %s.' % (len(args), args))
37 self.own_path = sys.argv[0]
38 self.java_path = _parse_nullable_argument(sys.argv[1])
39 self.saxon_path = _parse_nullable_argument(sys.argv[2])
40 self.xsltproc_path = _parse_nullable_argument(sys.argv[3])
41 self.xslt_path = _parse_nullable_argument(sys.argv[4])
42 self.input = sys.argv[5]
43 self.output = sys.argv[6]
44 self.script_folder = os.path.dirname(self.own_path) + '/../'
46 print('Generating ePub with the following parameters:')
49 print(self.saxon_path)
50 print(self.xsltproc_path)
55 # Precompute paths that will be used later.
56 self.output_dir = tempfile.mkdtemp().replace('\\', '/')
57 self.package_opf = self.output_dir + '/OEBPS/package.opf' # Does not exist yet,
58 print('Temporary output directory: %s' % self.output_dir)
60 if self.xslt_path is None:
61 self.xslt = self.script_folder + 'docbook/epub3/chunk.xsl'
63 self.xslt = self.xslt_path + '/epub3/chunk.xsl'
64 print('XSLT style sheet to use:')
67 if self.saxon_path is None:
68 self.saxon_path = self.script_folder + 'scripts/saxon6.5.5.jar'
70 # These will be filled during the execution of the script.
73 def gracefully_fail(self, reason):
74 print('docbook2epub fails: %s' % reason)
75 shutil.rmtree(self.output_dir, ignore_errors=True)
78 def start_xslt_transformation(self):
80 if self.xsltproc_path is not None:
81 command = self.start_xslt_transformation_xsltproc()
82 elif self.java_path is not None:
83 command = self.start_xslt_transformation_saxon6()
86 self.gracefully_fail('no XSLT processor available')
88 print('Command to execute:')
91 quoted_command = command
93 # On Windows, it is typical to have spaces in folder names, and that requires to wrap the whole command
94 # in quotes. On Linux, this might create errors when starting the command.
95 quoted_command = '"' + command + '"'
96 # This could be simplified by using subprocess.run, but this requires Python 3.5.
98 if os.system(quoted_command) != 0:
99 self.gracefully_fail('error from the XSLT processor')
101 print('Generated ePub contents.')
103 def start_xslt_transformation_xsltproc(self):
104 params = '-stringparam base.dir "' + self.output_dir + '"'
105 return '"' + self.xsltproc_path + '" ' + params + ' "' + self.xslt + '" "' + self.input + '"'
107 def start_xslt_transformation_saxon6(self):
108 params = 'base.dir=%s' % self.output_dir
109 executable = '"' + self.java_path + '" -jar "' + self.saxon_path + '"'
110 return executable + ' "' + self.input + '" "' + self.xslt + '" "' + params + '"'
112 def get_images_from_package_opf(self):
115 # Example in the OPF file:
116 # <item id="d436e1" href="D:/LyX/lib/images/buffer-view.svgz" media-type="image/SVGZ"/>
117 # The XHTML files are also <item> tags:
118 # <item id="id-d0e2" href="index.xhtml" media-type="application/xhtml+xml"/>
120 with open(self.package_opf, 'r') as f:
121 for line in f.readlines():
122 if '<item' in line and 'media-type="image' in line:
123 images.append(line.split('href="')[1].split('"')[0])
124 except FileNotFoundError:
125 print('The package.opf file was not found, probably due to a DocBook error. The ePub file will be corrupt.')
129 def change_image_paths(self, file):
130 # This could be optimised, as the same operation is performed a zillion times on many files:
131 # https://www.oreilly.com/library/view/python-cookbook/0596001673/ch03s15.html
132 with open(file, 'r', encoding='utf8') as f:
135 with open(file, 'w', encoding='utf8') as f:
136 for line in contents:
137 for (old, new) in self.renamed.items():
138 line = line.replace(old, new)
141 def copy_images(self):
142 # Copy the assets to the OEBPS/images/. All paths are available in OEBPS/package.opf, but they must also be
143 # changed in the XHTML files. Typically, the current paths are absolute.
145 # First, get the mapping old file => file in the ePub archive.
146 original_images = self.get_images_from_package_opf()
147 self.renamed = {img: 'images/' + os.path.basename(img) for img in original_images}
149 # Then, transform all paths (both OPF and XHTML files).
150 self.change_image_paths(self.output_dir + '/OEBPS/package.opf')
151 for file in glob.glob(self.output_dir + '/OEBPS/*.xhtml'):
152 self.change_image_paths(file)
154 # Ensure that the destination path exists. OEBPS exists due to the DocBook-to-ePub transformation.
155 if not os.path.exists(self.output_dir + '/OEBPS/images/'):
156 os.mkdir(self.output_dir + '/OEBPS/images/')
158 # Finally, actually copy the image files.
159 for (old, new) in self.renamed.items():
160 shutil.copyfile(old, self.output_dir + '/OEBPS/' + new)
162 def create_zip_archive(self):
163 with zipfile.ZipFile(self.output, 'w', zipfile.ZIP_DEFLATED) as zip:
164 # Python 3.5 brings the `recursive` argument. For older versions, this trick is required...
165 # for file in glob.glob(output_dir + '/**/*', recursive=True):
166 for file in [os.path.join(dp, f) for dp, dn, filenames in os.walk(self.output_dir) for f in filenames]:
167 zip.write(file, os.path.relpath(file, self.output_dir), compress_type=zipfile.ZIP_STORED)
169 shutil.rmtree(self.output_dir)
170 print('Generated ePub.')
173 self.start_xslt_transformation()
175 self.create_zip_archive()
178 if __name__ == '__main__':
179 DocBookToEpub(sys.argv).transform()