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
22 from io import open # Required for Python 2.
25 def _parse_nullable_argument(arg):
26 return arg if arg != '' and arg != 'none' else None
30 def __init__(self, args=None):
35 print('Seven arguments are expected, only %s found: %s.' % (len(args), args))
38 self.own_path = sys.argv[0]
39 self.java_path = _parse_nullable_argument(sys.argv[1])
40 self.saxon_path = _parse_nullable_argument(sys.argv[2])
41 self.xsltproc_path = _parse_nullable_argument(sys.argv[3])
42 self.xslt_path = _parse_nullable_argument(sys.argv[4])
43 self.input = sys.argv[5]
44 self.output = sys.argv[6]
45 self.script_folder = os.path.dirname(self.own_path) + '/../'
47 print('Generating ePub with the following parameters:')
50 print(self.saxon_path)
51 print(self.xsltproc_path)
56 # Precompute paths that will be used later.
57 self.output_dir = tempfile.mkdtemp().replace('\\', '/')
58 self.package_opf = self.output_dir + '/OEBPS/package.opf' # Does not exist yet,
59 print('Temporary output directory: %s' % self.output_dir)
61 if self.xslt_path is None:
62 self.xslt = self.script_folder + 'docbook/epub3/chunk.xsl'
64 self.xslt = self.xslt_path + '/epub3/chunk.xsl'
65 print('XSLT style sheet to use:')
68 if self.saxon_path is None:
69 self.saxon_path = self.script_folder + 'scripts/saxon6.5.5.jar'
71 # These will be filled during the execution of the script.
74 def gracefully_fail(self, reason):
75 print('docbook2epub fails: %s' % reason)
76 shutil.rmtree(self.output_dir, ignore_errors=True)
79 def start_xslt_transformation(self):
81 if self.xsltproc_path is not None:
82 command = self.start_xslt_transformation_xsltproc()
83 elif self.java_path is not None:
84 command = self.start_xslt_transformation_saxon6()
87 self.gracefully_fail('no XSLT processor available')
89 print('Command to execute:')
92 quoted_command = command
94 # On Windows, it is typical to have spaces in folder names, and that requires to wrap the whole command
95 # in quotes. On Linux, this might create errors when starting the command.
96 quoted_command = '"' + command + '"'
97 # This could be simplified by using subprocess.run, but this requires Python 3.5.
99 if os.system(quoted_command) != 0:
100 self.gracefully_fail('error from the XSLT processor')
102 print('Generated ePub contents.')
104 def start_xslt_transformation_xsltproc(self):
105 params = '-stringparam base.dir "' + self.output_dir + '"'
106 return '"' + self.xsltproc_path + '" ' + params + ' "' + self.xslt + '" "' + self.input + '"'
108 def start_xslt_transformation_saxon6(self):
109 params = 'base.dir=%s' % self.output_dir
110 executable = '"' + self.java_path + '" -jar "' + self.saxon_path + '"'
111 return executable + ' "' + self.input + '" "' + self.xslt + '" "' + params + '"'
113 def get_images_from_package_opf(self):
116 # Example in the OPF file:
117 # <item id="d436e1" href="D:/LyX/lib/images/buffer-view.svgz" media-type="image/SVGZ"/>
118 # The XHTML files are also <item> tags:
119 # <item id="id-d0e2" href="index.xhtml" media-type="application/xhtml+xml"/>
121 with open(self.package_opf, 'r') as f:
122 for line in f.readlines():
123 if '<item' in line and 'media-type="image' in line:
124 images.append(line.split('href="')[1].split('"')[0])
125 except FileNotFoundError:
126 print('The package.opf file was not found, probably due to a DocBook error. The ePub file will be corrupt.')
130 def change_image_paths(self, file):
131 # This could be optimised, as the same operation is performed a zillion times on many files:
132 # https://www.oreilly.com/library/view/python-cookbook/0596001673/ch03s15.html
133 with open(file, 'r', encoding='utf8') as f:
136 with open(file, 'w', encoding='utf8') as f:
137 for line in contents:
138 for (old, new) in self.renamed.items():
139 line = line.replace(old, new)
142 def copy_images(self):
143 # Copy the assets to the OEBPS/images/. All paths are available in OEBPS/package.opf, but they must also be
144 # changed in the XHTML files. Typically, the current paths are absolute.
146 # First, get the mapping old file => file in the ePub archive.
147 original_images = self.get_images_from_package_opf()
148 self.renamed = {img: 'images/' + os.path.basename(img) for img in original_images}
150 # Then, transform all paths (both OPF and XHTML files).
151 self.change_image_paths(self.output_dir + '/OEBPS/package.opf')
152 for file in glob.glob(self.output_dir + '/OEBPS/*.xhtml'):
153 self.change_image_paths(file)
155 # Ensure that the destination path exists. OEBPS exists due to the DocBook-to-ePub transformation.
156 if not os.path.exists(self.output_dir + '/OEBPS/images/'):
157 os.mkdir(self.output_dir + '/OEBPS/images/')
159 # Finally, actually copy the image files.
160 for (old, new) in self.renamed.items():
161 shutil.copyfile(old, self.output_dir + '/OEBPS/' + new)
163 def create_zip_archive(self):
164 with zipfile.ZipFile(self.output, 'w', zipfile.ZIP_DEFLATED) as zip:
165 # Python 3.5 brings the `recursive` argument. For older versions, this trick is required...
166 # for file in glob.glob(output_dir + '/**/*', recursive=True):
167 for file in [os.path.join(dp, f) for dp, dn, filenames in os.walk(self.output_dir) for f in filenames]:
168 zip.write(file, os.path.relpath(file, self.output_dir), compress_type=zipfile.ZIP_STORED)
170 shutil.rmtree(self.output_dir)
171 print('Generated ePub.')
174 self.start_xslt_transformation()
176 self.create_zip_archive()
179 if __name__ == '__main__':
180 DocBookToEpub(sys.argv).transform()