]> git.lyx.org Git - lyx.git/blob - lib/scripts/docbook2epub.py
GuiSearch: make search options visible/accessible in minimal mode
[lyx.git] / lib / scripts / docbook2epub.py
1 # -*- coding: utf-8 -*-
2
3 # file docbook2epub.py
4 # This file is part of LyX, the document processor.
5 # Licence details can be found in the file COPYING.
6 #
7 # \author Thibaut Cuvelier
8 #
9 # Full author contact details are available in file CREDITS
10
11 # Usage:
12 #   python docbook2epub.py java_binary saxon_path xsltproc_path xslt_path in.docbook out.epub
13
14 from __future__ import print_function
15
16 import glob
17 import os
18 import shutil
19 import sys
20 import tempfile
21 import zipfile
22 from io import open  # Required for Python 2.
23
24
25 def _parse_nullable_argument(arg):
26     return arg if arg != '' and arg != 'none' else None
27
28
29 class DocBookToEpub:
30     def __init__(self, args=None):
31         if args is None:
32             args = sys.argv
33
34         if len(args) != 7:
35             print('Seven arguments are expected, only %s found: %s.' % (len(args), args))
36             sys.exit(1)
37
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) + '/../'
46
47         print('Generating ePub with the following parameters:')
48         print(self.own_path)
49         print(self.java_path)
50         print(self.saxon_path)
51         print(self.xsltproc_path)
52         print(self.xslt_path)
53         print(self.input)
54         print(self.output)
55
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)
60
61         if self.xslt_path is None:
62             self.xslt = self.script_folder + 'docbook/epub3/chunk.xsl'
63         else:
64             self.xslt = self.xslt_path + '/epub3/chunk.xsl'
65         print('XSLT style sheet to use:')
66         print(self.xslt)
67
68         if self.saxon_path is None:
69             self.saxon_path = self.script_folder + 'scripts/saxon6.5.5.jar'
70
71         # These will be filled during the execution of the script.
72         self.renamed = None
73
74     def gracefully_fail(self, reason):
75         print('docbook2epub fails: %s' % reason)
76         shutil.rmtree(self.output_dir, ignore_errors=True)
77         sys.exit(1)
78
79     def start_xslt_transformation(self):
80         command = None
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()
85
86         if command is None:
87             self.gracefully_fail('no XSLT processor available')
88
89         print('Command to execute:')
90         print(command)
91
92         quoted_command = command
93         if os.name == 'nt':
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.
98
99         if os.system(quoted_command) != 0:
100             self.gracefully_fail('error from the XSLT processor')
101
102         print('Generated ePub contents.')
103
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 + '"'
107
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 + '"'
112
113     def get_images_from_package_opf(self):
114         images = []
115
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"/>
120         try:
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.')
127
128         return images
129
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:
134             contents = list(f)
135
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)
140                 f.write(line)
141
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.
145
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}
149
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)
154
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/')
158
159         # Finally, actually copy the image files.
160         for (old, new) in self.renamed.items():
161             shutil.copyfile(old, self.output_dir + '/OEBPS/' + new)
162
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)
169
170         shutil.rmtree(self.output_dir)
171         print('Generated ePub.')
172
173     def transform(self):
174         self.start_xslt_transformation()
175         self.copy_images()
176         self.create_zip_archive()
177
178
179 if __name__ == '__main__':
180     DocBookToEpub(sys.argv).transform()