-
Notifications
You must be signed in to change notification settings - Fork 1
/
create-gallery.py
executable file
·73 lines (56 loc) · 2.45 KB
/
create-gallery.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
import os
import re
import sys
import shutil
import argparse
GALLERY_TEMPLATE = os.path.join(os.path.dirname(__file__), './gallery.template')
IMAGE_EXT = ['.png', '.jpg', '.jpeg']
IMAGE_HTML = '<img class="hidden" data-src="{image}" alt="Loading photo..." />'
def main():
p = argparse.ArgumentParser(description='Generate a simple one-page HTML gallery.')
p.add_argument('-i', '--input', dest='in_dir', required=True,
action='store', help='input directory where images are located')
p.add_argument('-o', '--output', dest='out_dir',
action='store', help='output directory (default: "./gallery")')
p.add_argument('-t', '--title', dest='title',
action='store', help='title to be used in the <title> tag of the HTML (default: Gallery)')
args = p.parse_args()
if not os.path.isdir(args.in_dir):
p.error('The specified location is not a valid directory')
# Default title is 'Gallery'
title = args.title if args.title else 'Gallery'
# Default output is './gallery'
out_dir = args.out_dir.rstrip('/') if args.out_dir else './gallery'
# Overwriting is dangerous, quitting is safer
if os.path.exists(out_dir):
print('ERROR: Directory {} already exists. Remove it or specify a different one.'.format(out_dir))
sys.exit(1)
file_list = os.listdir(args.in_dir)
# Filter out non-image files
img_file_list = []
for f in file_list:
_, file_ext = os.path.splitext(f)
if file_ext.lower() in IMAGE_EXT:
img_file_list.append(f)
else:
print('Skipping {} -- not an image file'.format(f))
if not img_file_list:
print('ERROR: Did not locate any image files in {}'.format(args.in_dir))
sys.exit(1)
# Open gallery.html template and add images and title
with open(GALLERY_TEMPLATE) as f:
template = f.read()
html = re.sub(r'{{ TITLE }}', title, template)
photos_html = [IMAGE_HTML.format(image=image) for image in sorted(img_file_list)]
html = re.sub(r'{{ PHOTOS }}', '\n'.join(photos_html), html)
# Create output directory
print('Created directory: {}'.format(out_dir))
os.makedirs(out_dir)
# Write out HTML file
with open(os.path.join(out_dir, 'index.html'), 'w') as f:
f.write(html)
# Copy all image files
for f in img_file_list:
shutil.copy('{}/{}'.format(args.in_dir.rstrip('/'), f), out_dir)
if __name__ == '__main__':
main()