-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslides35.py
executable file
·391 lines (349 loc) · 11.7 KB
/
slides35.py
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
#!/usr/bin/env python
""" Roadmap
Change number in one SVG file in Python
Change image in one SVG file
Make a list of JPG files sorted by date
Make SVG files from JPG files with adequate numbering and file naming
"""
SLIDES35_DEFAULT_SVG_TEMPLATE = "templates/36x24mmNumbered.svg"
SLIDES35_DEFAULT_OUTPUT_DPI = 500
SLIDES35_DEFAULT_OUTPUT_PREFIX = "slide_"
SLIDES35_DEFAULT_OUTPUT_FILENAME_ZFILL_COUNT = 3
SLIDES35_DEFAULT_SVG_TO_PNG_CONVERTER = "convert"
SLIDES35_SUPPORTED_CONVERTERS = ("inkscape", "convert", "rsvg-convert")
from pathlib import Path
from xml.dom import minidom
import argparse
import os
import subprocess
import shutil
import tempfile
class Slide:
_id = None
_comment = None
_picture = None
_template = None
_prefix = None
_verbose = None
_converter = None
def __init__(
self,
template=None,
verbose=False,
converter=SLIDES35_DEFAULT_SVG_TO_PNG_CONVERTER,
):
self.template(template)
self.verbose(verbose)
self.converter(converter)
def template(self, template=None):
if not template:
return self._template
else:
if not Path(template).exists():
raise FileNotFoundError("Could not find template: {}".format(template))
self._template = str(Path(template))
return self
def converter(self, converter=None):
if not converter:
return self._converter
else:
if type(converter) is not str:
raise TypeError("converter must be a str")
if converter not in SLIDES35_SUPPORTED_CONVERTERS:
raise ValueError(
"converter must be one {}".format(SLIDES35_SUPPORTED_CONVERTERS)
)
self._converter = converter
return self
def verbose(self, verbose=None):
if verbose is None:
return self._verbose
else:
if type(verbose) is not bool:
raise TypeError("verbose flag must be a boolean")
self._verbose = verbose
return self
def id(self, page_id=None):
if not page_id:
return self._id
else:
self._id = page_id
return self
def comment(self, comment=None):
if not comment:
return self._comment
else:
self._comment = comment
return self
def picture(self, picture=None):
if not picture:
return self._picture
else:
if not Path(picture).exists():
raise FileNotFoundError("Could not find picture: {}".format(picture))
self._picture = str(Path(picture).resolve())
return self
def prefix(self, prefix=None):
if not prefix:
return self._prefix
else:
self._prefix = str(prefix)
return self
def svg(self, output_path=None):
if not self._template or not Path(self._template).exists():
raise FileNotFoundError("Set the SVG template first")
if not self._id:
raise ValueError("Set the .id() value first")
if not self._picture:
raise ValueError("Set the .picture() value first")
rootElem = minidom.parse(self._template)
rootElem.getElementsByTagName("image")[0].attributes[
"xlink:href"
].value = self._picture
rootElem.getElementsByTagName("text")[0].firstChild.firstChild.nodeValue = str(
self._id
).center(3)
if output_path:
if self._verbose:
print(
"{} -> {} (id: {}) -> {}".format(
self._picture, self._template, self._id, output_path
)
)
with open(output_path, "w") as f:
f.write(rootElem.toxml())
return self
else:
return rootElem.toxml()
def png(
self,
output_path,
dpi=SLIDES35_DEFAULT_OUTPUT_DPI,
):
if not shutil.which(self._converter):
print(
"Cannot find executable path for converter '{}'".format(self._converter)
)
exit(1)
svg_handle, svg_output_filename = tempfile.mkstemp(".svg")
self.svg(svg_output_filename)
dpi = dpi if dpi else SLIDES35_DEFAULT_OUTPUT_DPI
if self._verbose:
print("{} -> {}".format(svg_output_filename, output_path))
if self._converter == "convert":
command_to_run = [
"convert",
"-resample",
str(dpi),
svg_output_filename,
output_path,
]
elif self._converter == "inkscape":
command_to_run = [
"inkscape",
svg_output_filename,
"--export-dpi",
str(dpi),
"--export-filename",
output_path,
]
elif self._converter == "rsvg-convert":
command_to_run = [
"rsvg-convert",
"--dpi-x=" + str(dpi),
"--dpi-y=" + str(dpi),
"-o",
output_path,
svg_output_filename,
]
if self._verbose:
print(command_to_run)
subprocess.run(command_to_run)
os.unlink(svg_output_filename)
return self
def __eq__(self, other):
return (
self._template == other._template
and self._id == other._id
and self._comment == other._comment
and self._picture == other._picture
)
def do_slide(
template,
picture,
identifier,
output_dir=".",
stdout=False,
output_filename=None,
output_as="svg",
output_prefix=SLIDES35_DEFAULT_OUTPUT_PREFIX,
dpi=SLIDES35_DEFAULT_OUTPUT_DPI,
converter=SLIDES35_DEFAULT_SVG_TO_PNG_CONVERTER,
verbose=False,
):
if output_as not in ("svg", "png"):
raise ValueError(
"output_as parameter must be 'svg' or 'png' but '{}' was provided"
)
if not output_filename:
output_path = "{}{}.{}".format(
output_prefix,
(str(identifier).zfill(SLIDES35_DEFAULT_OUTPUT_FILENAME_ZFILL_COUNT)),
output_as,
)
else:
output_path = output_filename
output_path = Path(output_dir) / output_path
s = (
Slide(template)
.picture(picture)
.id(identifier)
.verbose(verbose)
.converter(converter)
)
if output_as == "svg":
if not stdout:
s.svg(output_path)
else:
print(s.svg())
else:
s.png(output_path=output_path, dpi=dpi)
return output_path
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--picture", help="path to picture to embed")
parser.add_argument(
"-I", "--pictures-dir", nargs="?", help="Path to directory of pictures to embed"
)
parser.add_argument("-n", "--id", help="ID of the new slide")
parser.add_argument(
"-t",
"--template",
default=SLIDES35_DEFAULT_SVG_TEMPLATE,
help="SVG template to use (default:{}).".format(SLIDES35_DEFAULT_SVG_TEMPLATE),
)
parser.add_argument(
"-0",
"--stdout",
help="Output SVG to STDOUT instead of a file. Only for SVG output (ie. without --output or with --output providing a .svg-ending filename).",
action="store_true",
)
parser.add_argument(
"-o",
"--output",
nargs="?",
help="Output file name (or file name --picture-dir is used). If omitted, result is printed. This cannot be used with --output-prefix.",
)
parser.add_argument(
"-c",
"--converter",
nargs="?",
default=SLIDES35_DEFAULT_SVG_TO_PNG_CONVERTER,
help="Executable to use to convert temporary SVG files to PNG (default:{}).".format(
SLIDES35_DEFAULT_SVG_TO_PNG_CONVERTER
),
)
parser.add_argument(
"-v", "--verbose", action="store_true", help="Enabled verbose output."
)
parser.add_argument(
"-p",
"--output-prefix",
nargs="?",
help="Output file name prefix, which will be suffixed with a 3-digits integer (using --identifier or not if --pictures-dir is used). This option cannot be used with --output.",
)
parser.add_argument("-d", "--output-dir", nargs="?", help="Output file directory")
parser.add_argument(
"--dpi",
nargs="?",
default=SLIDES35_DEFAULT_OUTPUT_DPI,
help="DPI dots-per-inch density for PNG output (default:{})".format(
SLIDES35_DEFAULT_OUTPUT_DPI
),
)
args = parser.parse_args()
if not args.picture and not args.pictures_dir:
print("No --picture or --pictures-dir provided. Exitting")
exit(1)
if args.picture and args.pictures_dir:
print("Provide either --picture or --pictures-dir, not both. Exitting")
exit(1)
if not args.id and not args.pictures_dir:
print(
"No --id provided (while not in a --pictures-dir input files situation). Exitting"
)
exit(1)
if args.output_prefix and args.output:
print("You cannot use --output-prefix and --output together")
exit(1)
if args.stdout and args.output:
print("You cannot use --output (filename) and --stdout together")
exit(1)
if args.output_dir:
if not Path(args.output_dir).exists():
os.makedirs(args.output_dir, exist_ok=True)
output_dir = Path(args.output_dir if args.output_dir else ".")
if args.pictures_dir:
if args.stdout:
print("--pictures-dir cannot be used with --stdout. Exitting")
exit(1)
pic_dir = Path(args.pictures_dir)
if not pic_dir.exists():
print(
"--pictures-dir directory {} does not exist. Exitting".format(pic_dir)
)
exit(1)
img_id = 1
for img in sorted(os.listdir(pic_dir)):
img_path = (Path(pic_dir) / Path(img)).resolve()
output_prefix = (
args.output_prefix
if args.output_prefix
else SLIDES35_DEFAULT_OUTPUT_PREFIX
)
do_slide(
template=args.template,
picture=img_path,
identifier=img_id,
output_dir=output_dir,
output_as="png",
output_prefix=output_prefix,
verbose=args.verbose,
converter=args.converter,
)
img_id += 1
exit(0)
export_to_png = False
output_filename = args.output
if args.output and output_filename.lower().endswith(".png"):
export_to_png = True
picture = Path(args.picture).resolve()
if args.stdout:
if export_to_png:
print(
"The --stdout SVG-outputting option cannot be used with .png output (see the suffix of your --output argument)"
)
exit(1)
else:
do_slide(
template=args.template,
picture=picture,
stdout=True,
identifier=args.id,
verbose=args.verbose,
)
else:
output_file_format = "png" if export_to_png else "svg"
do_slide(
template=args.template,
picture=picture,
identifier=args.id,
output_filename=output_filename,
output_dir=output_dir,
output_as=output_file_format,
dpi=args.dpi,
verbose=args.verbose,
converter=args.converter,
)
if __name__ == "__main__":
main()