-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathfoto4lb.py
More file actions
172 lines (158 loc) · 5.04 KB
/
foto4lb.py
File metadata and controls
172 lines (158 loc) · 5.04 KB
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
#!/usr/bin/env python
# file: foto4lb.py
# vim:fileencoding=utf-8:ft=python
#
# Copyright © 2011-2019 R.F. Smith <rsmith@xs4all.nl>.
# SPDX-License-Identifier: MIT
# Created: 2011-11-07T21:40:58+01:00
# Last modified: 2024-01-05T23:25:38+0100
"""Shrink fotos to a size suitable for use in my logbook."""
from datetime import datetime
import argparse
import concurrent.futures as cf
import logging
import os
import subprocess as sp
import sys
# For performance measurments
# import time
from PIL import Image
from PIL.ExifTags import TAGS
__version__ = "2024.01.05"
outdir = "foto4lb"
extensions = (".jpg", ".jpeg", ".raw")
def main():
"""
Entry point for foto4lb.
"""
args = setup()
pairs = []
count = 0
for path in args.path:
if os.path.exists(path + os.sep + outdir):
logging.warning(
f'"{outdir}" already exists in "{path}", skipping this path.'
)
continue
files = [
f.name
for f in os.scandir(path)
if f.is_file() and f.name.lower().endswith(extensions)
]
count += len(files)
pairs.append((path, files))
logging.debug(f'Path: "{path}"')
logging.debug(f"Files: {files}")
if len(pairs) == 0:
logging.info("nothing to do.")
return
logging.info(f"found {count} files.")
logging.info("creating output directories.")
for dirname, _ in pairs:
os.mkdir(dirname + os.sep + outdir)
infodict = {
0: "file '{}' processed.",
1: "file '{}' is not an image, skipped.",
2: "error running convert on '{}'.",
}
# For performance measurements.
# start = time.monotonic()
with cf.ThreadPoolExecutor(max_workers=os.cpu_count()) as tp:
agen = ((p, fn, args.width) for p, flist in pairs for fn in flist)
for fn, rv in tp.map(processfile, agen):
logging.info(infodict[rv].format(fn))
# For performance measurements.
# dt = time.monotonic() - start
# logging.info(f'startup preparations took {dt:.2f} s')
def setup():
"""Process the command-line arguments."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"-w",
"--width",
default=1920,
type=int,
help="width of the images in pixels (default 1920)",
)
parser.add_argument(
"--log",
default="warning",
choices=["debug", "info", "warning", "error"],
help="logging level (defaults to 'warning')",
)
parser.add_argument("-v", "--version", action="version", version=__version__)
parser.add_argument("path", nargs="*", help="directory in which to work")
args = parser.parse_args(sys.argv[1:])
logging.basicConfig(
level=getattr(logging, args.log.upper(), None),
format="%(levelname)s: %(message)s",
)
logging.debug(f"Command line arguments = {sys.argv}")
logging.debug(f"Parsed arguments = {args}")
if not args.path:
parser.print_help()
sys.exit(0)
# Check for required programs.
try:
sp.run(["convert"], stdout=sp.DEVNULL, stderr=sp.DEVNULL)
logging.debug("found “convert”")
except FileNotFoundError:
logging.error("the program “convert” cannot be found")
sys.exit(1)
return args
def processfile(packed):
"""
Read an image file and write a smaller version.
Arguments:
packed: A 3-tuple of (path, filename, output width)
Returns:
A 2-tuple (input file name, status).
Status 0 indicates a succesful conversion,
status 1 means that the input file was not a recognized image format,
status 2 means a subprocess error.
"""
# For performance measurements.
# start = time.monotonic()
path, name, newwidth = packed
fname = os.sep.join([path, name])
oname = os.sep.join([path, outdir, name.lower()])
try:
img = Image.open(fname)
ld = {}
for tag, value in img._getexif().items():
decoded = TAGS.get(tag, tag)
ld[decoded] = value
want = set(["DateTime", "DateTimeOriginal", "CreateDate", "DateTimeDigitized"])
available = sorted(list(want.intersection(set(ld.keys()))))
fields = ld[available[0]].replace(" ", ":").split(":")
dt = datetime(*map(int, fields))
except Exception:
logging.warning("exception raised when reading the file time.")
dt = datetime.today()
args = [
"convert",
fname,
"-strip",
"-resize",
str(newwidth),
"-units",
"PixelsPerInch",
"-density",
"300",
"-unsharp",
"2x0.5+0.7+0",
"-quality",
"80",
oname,
]
rp = sp.run(args, stdout=sp.DEVNULL, stderr=sp.DEVNULL)
if rp.returncode != 0:
return (name, 2)
modtime = dt.timestamp()
os.utime(oname, (modtime, modtime))
# For performance measurements.
# dt = time.monotonic() - start
# logging.info(f'processfile took {dt:.2f} s')
return (fname, 0)
if __name__ == "__main__":
main()