]> git.lyx.org Git - lyx.git/blob - lib/scripts/docbook2epub.py
1d39962be54b18b1cdd815e96c842972daf6cf33
[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 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
23
24 def _parse_nullable_argument(arg):
25     return arg if arg != '' and arg != 'none' else None
26
27
28 class DocBookToEpub:
29     def __init__(self, args=None):
30         if args is None:
31             args = sys.argv
32
33         if len(args) != 7:
34             print('Seven arguments are expected, only %s found: %s.' % (len(args), args))
35             sys.exit(1)
36
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) + '/../'
45
46         print('Generating ePub with the following parameters:')
47         print(self.own_path)
48         print(self.java_path)
49         print(self.saxon_path)
50         print(self.xsltproc_path)
51         print(self.xslt_path)
52         print(self.input)
53         print(self.output)
54
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)
59
60         if self.xslt_path is None:
61             self.xslt = self.script_folder + 'docbook/epub3/chunk.xsl'
62         else:
63             self.xslt = self.xslt_path + '/epub3/chunk.xsl'
64         print('XSLT style sheet to use:')
65         print(self.xslt)
66
67         if self.saxon_path is None:
68             self.saxon_path = self.script_folder + 'scripts/saxon6.5.5.jar'
69
70         # These will be filled during the execution of the script.
71         self.renamed = None
72
73     def gracefully_fail(self, reason):
74         print('docbook2epub fails: %s' % reason)
75         shutil.rmtree(self.output_dir, ignore_errors=True)
76         sys.exit(1)
77
78     def start_xslt_transformation(self):
79         command = None
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()
84
85         if command is None:
86             self.gracefully_fail('no XSLT processor available')
87
88         print('Command to execute:')
89         print(command)
90
91         quoted_command = command
92         if os.name == 'nt':
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.
97
98         if os.system(quoted_command) != 0:
99             self.gracefully_fail('error from the XSLT processor')
100
101         print('Generated ePub contents.')
102
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 + '"'
106
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 + '"'
111
112     def get_images_from_package_opf(self):
113         images = []
114
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"/>
119         try:
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.')
126
127         return images
128
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:
133             contents = list(f)
134
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)
139                 f.write(line)
140
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.
144
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}
148
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)
153
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/')
157
158         # Finally, actually copy the image files.
159         for (old, new) in self.renamed.items():
160             shutil.copyfile(old, self.output_dir + '/OEBPS/' + new)
161
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)
168
169         shutil.rmtree(self.output_dir)
170         print('Generated ePub.')
171
172     def transform(self):
173         self.start_xslt_transformation()
174         self.copy_images()
175         self.create_zip_archive()
176
177
178 if __name__ == '__main__':
179     DocBookToEpub(sys.argv).transform()