Skip to content

Commit d4bbf4f

Browse files
committed
pykern fmt
1 parent e7068d9 commit d4bbf4f

File tree

13 files changed

+344
-283
lines changed

13 files changed

+344
-283
lines changed

rnpix/base_pkconfig.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
# -*- coding: utf-8 -*-
2-
u"""Default config
2+
"""Default config
33
44
:copyright: Copyright (c) 2016 Robert Nagler. All Rights Reserved.
55
:license: http://www.apache.org/licenses/LICENSE-2.0.html
66
"""
77
from __future__ import absolute_import, division, print_function
88

9+
910
def alpha():
1011
return {}
1112

rnpix/common.py

Lines changed: 45 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# -*- coding: utf-8 -*-
2-
u"""Common code
2+
"""Common code
33
44
:copyright: Copyright (c) 2017 Robert Nagler. All Rights Reserved.
55
:license: http://www.apache.org/licenses/LICENSE-2.0.html
@@ -17,37 +17,37 @@
1717
import time
1818

1919

20-
_MOVIES = '3gp|mp4|mov|mpg|avi|mts|m4v'
20+
_MOVIES = "3gp|mp4|mov|mpg|avi|mts|m4v"
2121

2222
# icns is for unit testing
23-
_NEED_JPG = 'icns|dng|pcd|arw|skp'
23+
_NEED_JPG = "icns|dng|pcd|arw|skp"
2424

25-
_STILL = 'jpg|heic|png|tif|gif|psd|pdf|thm|jpeg'
25+
_STILL = "jpg|heic|png|tif|gif|psd|pdf|thm|jpeg"
2626

2727
STILL = re.compile(
28-
r'^(.+)\.({}|{}|{})$'.format(_STILL, _MOVIES, _NEED_JPG),
28+
r"^(.+)\.({}|{}|{})$".format(_STILL, _MOVIES, _NEED_JPG),
2929
flags=re.IGNORECASE,
3030
)
3131

3232
MOVIE = re.compile(
33-
r'^(.+)\.({})$'.format(_MOVIES),
33+
r"^(.+)\.({})$".format(_MOVIES),
3434
flags=re.IGNORECASE,
3535
)
3636

3737
NEED_PREVIEW = re.compile(
38-
r'^(.+)\.({})$'.format(_NEED_JPG + '|' + _MOVIES),
38+
r"^(.+)\.({})$".format(_NEED_JPG + "|" + _MOVIES),
3939
flags=re.IGNORECASE,
4040
)
4141

42-
THUMB_DIR = re.compile('^(?:200|50)$')
42+
THUMB_DIR = re.compile("^(?:200|50)$")
4343

4444

4545
@contextlib.contextmanager
4646
def user_lock():
4747
# Lock directories don't work within Dropbox folders, because
4848
# Dropbox uploads them and they can hang around after deleting here.
49-
lock_d = '/tmp/rnpix-lock-' + os.environ['USER']
50-
lock_pid = os.path.join(lock_d, 'pid')
49+
lock_d = "/tmp/rnpix-lock-" + os.environ["USER"]
50+
lock_pid = os.path.join(lock_d, "pid")
5151

5252
def _pid():
5353
res = -1
@@ -73,21 +73,21 @@ def _pid():
7373
try:
7474
os.mkdir(lock_d)
7575
is_locked = True
76-
with open(lock_pid, 'w') as f:
76+
with open(lock_pid, "w") as f:
7777
f.write(str(os.getpid()))
7878
break
7979
except OSError as e:
8080
if e.errno != errno.EEXIST:
8181
raise
8282
pid = _pid()
8383
if pid <= 0:
84-
time.sleep(.4)
84+
time.sleep(0.4)
8585
continue
8686
if pid == _pid():
8787
os.remove(lock_pid)
8888
os.rmdir(lock_d)
8989
else:
90-
raise ValueError('{}: unable to create lock'.format(lock_d))
90+
raise ValueError("{}: unable to create lock".format(lock_d))
9191
yield lock_d
9292
finally:
9393
if is_locked:
@@ -97,79 +97,85 @@ def _pid():
9797

9898
def move_one(src, dst_root):
9999
e = src.ext.lower()
100-
if e == '.jpeg':
101-
e = '.jpg'
102-
f1 = '%Y-%m-%d-%H.%M.%S'
103-
f2 = '{}-{}-{}-{}.{}.{}'
100+
if e == ".jpeg":
101+
e = ".jpg"
102+
f1 = "%Y-%m-%d-%H.%M.%S"
103+
f2 = "{}-{}-{}-{}.{}.{}"
104104
# CreationDate is in timezone as is DateTimeOriginal but not for movies
105-
z = ('-CreationDate', '-CreationDateValue', '-createdate') if MOVIE.search(src.basename) else ('-DateTimeOriginal',)
105+
z = (
106+
("-CreationDate", "-CreationDateValue", "-createdate")
107+
if MOVIE.search(src.basename)
108+
else ("-DateTimeOriginal",)
109+
)
106110
d = None
107111
for y in z:
108112
p = subprocess.run(
109-
('exiftool', '-d', f1, y, '-S', '-s', src),
113+
("exiftool", "-d", f1, y, "-S", "-s", src),
110114
stdout=subprocess.PIPE,
111115
stderr=subprocess.PIPE,
112116
universal_newlines=True,
113117
)
114118
if p.returncode != 0:
115-
pykern.pkcli.command_error('exiftool failed: {} {}'.format(src, p.stderr))
116-
m = re.search(r'((?:20|19)\d\d)\D(\d\d)\D(\d\d)\D(\d\d)\D(\d\d)\D(\d\d)', str(p.stdout))
119+
pykern.pkcli.command_error("exiftool failed: {} {}".format(src, p.stderr))
120+
m = re.search(
121+
r"((?:20|19)\d\d)\D(\d\d)\D(\d\d)\D(\d\d)\D(\d\d)\D(\d\d)", str(p.stdout)
122+
)
117123
if m:
118124
# Creation Date Value is 2021:03:15 07:10:01-06:00
119125
# it's not a date, just a string but it has timezone
120126
t = f2.format(*m.groups())
121-
d = '{}/{}-{}'.format(*m.groups())
127+
d = "{}/{}-{}".format(*m.groups())
122128
break
123129
if not d:
124130
d = datetime.datetime.fromtimestamp(src.mtime())
125131
t = d.strftime(f1)
126-
d = d.strftime('%Y/%m-%d')
127-
pkdlog('use mtime: {} => {}', src, t)
132+
d = d.strftime("%Y/%m-%d")
133+
pkdlog("use mtime: {} => {}", src, t)
128134
if dst_root:
129135
d = dst_root.join(d)
130136
pykern.pkio.mkdir_parent(d)
131137
else:
132-
d = pykern.pkio.py_path('.')
138+
d = pykern.pkio.py_path(".")
133139
f = d.join(t + e)
134140
if f == src:
135-
pkdlog('ignoring same name: {}', src, f)
141+
pkdlog("ignoring same name: {}", src, f)
136142
return
137-
pkdlog('src {}', src)
143+
pkdlog("src {}", src)
138144
if f.exists():
139145
for i in range(1, 10):
140-
if f.read('rb') == src.read('rb'):
141-
pkdlog('removing dup={} keep={}', src, f)
146+
if f.read("rb") == src.read("rb"):
147+
pkdlog("removing dup={} keep={}", src, f)
142148
src.remove(ignore_errors=True)
143149
return
144-
f = d.join('{}-{}{}'.format(t, i, e))
150+
f = d.join("{}-{}{}".format(t, i, e))
145151
if not f.exists():
146152
break
147153
else:
148-
raise AssertionError('{}: exists'.format(f))
154+
raise AssertionError("{}: exists".format(f))
149155
if src.dirname == f.dirname:
150156
_fix_index(src.dirpath(), src.basename, f.basename)
151-
pkdlog('mv {} {}', src.basename, f.basename)
157+
pkdlog("mv {} {}", src.basename, f.basename)
152158
src.rename(f)
153-
pkdlog('dst {}', f)
159+
pkdlog("dst {}", f)
154160
return f
155161

156162

157163
def root():
158-
r = os.getenv('RNPIX_ROOT')
159-
assert r, 'must set $RNPIX_ROOT'
164+
r = os.getenv("RNPIX_ROOT")
165+
assert r, "must set $RNPIX_ROOT"
160166
return pykern.pkio.py_path(r)
161167

162168

163169
def _fix_index(d, old, new):
164-
i = d.join('index.txt')
170+
i = d.join("index.txt")
165171
if not i.exists():
166172
return
167173
r = []
168-
for l in i.read().split('\n'):
174+
for l in i.read().split("\n"):
169175
if len(l.strip()) <= 0:
170176
continue
171177
if l.startswith(old):
172-
pkdlog('updating index: {} => {}', old, new)
178+
pkdlog("updating index: {} => {}", old, new)
173179
l = l.replace(old, new)
174180
r.append(l)
175-
i.write('\n'.join(r) + '\n')
181+
i.write("\n".join(r) + "\n")

rnpix/pkcli/dedup.py

Lines changed: 21 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# -*- coding: utf-8 -*-
2-
u"""deduplicate
2+
"""deduplicate
33
44
:copyright: Copyright (c) 2021 Robert Nagler. All Rights Reserved.
55
:license: http://www.apache.org/licenses/LICENSE-2.0.html
@@ -17,16 +17,15 @@
1717
import time
1818

1919

20-
def find(path, nowrite=False, overwrite=False, skip=''):
21-
"""deduplicate images using $RNPIX_ROOT/dedup.db
22-
"""
20+
def find(path, nowrite=False, overwrite=False, skip=""):
21+
"""deduplicate images using $RNPIX_ROOT/dedup.db"""
2322
r = rnpix.common.root()
2423
i = 0
2524
if skip:
2625
skip = pykern.pkio.py_path(skip)
2726
with dbm.ndbm.open(
28-
str(pykern.pkio.py_path(r).join('dedup')),
29-
'c',
27+
str(pykern.pkio.py_path(r).join("dedup")),
28+
"c",
3029
) as m:
3130
for p in _walk(path):
3231
if skip:
@@ -35,36 +34,32 @@ def find(path, nowrite=False, overwrite=False, skip=''):
3534
continue
3635
i += 1
3736
if i % 10 == 0:
38-
print('#sleep 3')
37+
print("#sleep 3")
3938
time.sleep(2)
4039
s, p = _signature(p)
4140
if s in m and not overwrite:
4241
o = pykern.pkio.py_path(m[s].decode())
4342
if o == p:
4443
# same path
4544
continue
46-
if (
47-
o.dirname == p.dirname
48-
and o.purebasename.startswith(p.purebasename)
49-
):
45+
if o.dirname == p.dirname and o.purebasename.startswith(p.purebasename):
5046
# remove original, because longer (e.g. x-1.jpg)
5147
m[s] = str(p).encode()
5248
p = o
5349
x = f'"{p}"' if "'" in str(p) else f"'{p}'"
54-
print(f'#OLD {m[s].decode()}\nrm {x}')
50+
print(f"#OLD {m[s].decode()}\nrm {x}")
5551
else:
56-
print(f'#NEW {p}')
52+
print(f"#NEW {p}")
5753
if not nowrite:
5854
m[s] = str(p).encode()
5955

6056

6157
def not_in_db(path):
62-
"""deduplicate images using $RNPIX_ROOT/dedup.db
63-
"""
58+
"""deduplicate images using $RNPIX_ROOT/dedup.db"""
6459
r = rnpix.common.root()
6560
with dbm.ndbm.open(
66-
str(pykern.pkio.py_path(r).join('dedup')),
67-
'r',
61+
str(pykern.pkio.py_path(r).join("dedup")),
62+
"r",
6863
) as m:
6964
v = set([m[k] for k in m.keys()])
7065
for p in _walk(path, print_cd=False):
@@ -73,22 +68,25 @@ def not_in_db(path):
7368

7469

7570
def _signature(path):
76-
if path.ext.lower() in ('.jpg', '.jpeg'):
71+
if path.ext.lower() in (".jpg", ".jpeg"):
7772
try:
78-
return (subprocess.check_output(('identify', '-format', '%#', str(path))), path)
73+
return (
74+
subprocess.check_output(("identify", "-format", "%#", str(path))),
75+
path,
76+
)
7977
except subprocess.CalledProcessError:
8078
# weird thing: bunch of JPG files that are quicktime movies
81-
if b'QuickTime movie' not in subprocess.check_output(('file', str(path))):
79+
if b"QuickTime movie" not in subprocess.check_output(("file", str(path))):
8280
raise
83-
n = path.new(ext='.mov')
81+
n = path.new(ext=".mov")
8482
assert not n.exists()
8583
path.rename(n)
8684
path = n
8785
return (hashlib.md5(path.read_binary()).digest(), path)
8886

8987

9088
def _walk(path, print_cd=True):
91-
c = ''
89+
c = ""
9290
for p in pykern.pkio.walk_tree(path):
9391
if (
9492
p.islink()
@@ -97,6 +95,6 @@ def _walk(path, print_cd=True):
9795
):
9896
continue
9997
if print_cd and c != p.dirname:
100-
print(f'#CD {p.dirname}')
98+
print(f"#CD {p.dirname}")
10199
c = p.dirname
102100
yield p

0 commit comments

Comments
 (0)