Revision bc85feeb
Added by David Sorber over 7 years ago
| software/misc/sort_pics.py | ||
|---|---|---|
|
#!/usr/bin/python3
|
||
|
import datetime
|
||
|
import os
|
||
|
import pprint
|
||
|
import shutil
|
||
|
import sys
|
||
|
|
||
|
from PIL import Image
|
||
|
from PIL.ExifTags import TAGS
|
||
|
|
||
|
SOURCE_DIR = '/home/dsorber/Desktop/photos'
|
||
|
|
||
|
DT_FMT = '%Y:%m:%d %H:%M:%S'
|
||
|
|
||
|
# Sort JPEGs in SOURCE_DIR and write to DEST_DIR/<year>/<month> by reading
|
||
|
# EXIF tags
|
||
|
|
||
|
# Read EXIF tag information
|
||
|
# https://www.blog.pythonlibrary.org/2010/03/28/getting-photo-metadata-exif-using-python/
|
||
|
def get_exif(fn):
|
||
|
ret = {}
|
||
|
i = Image.open(fn)
|
||
|
info = i._getexif()
|
||
|
for tag, value in info.items():
|
||
|
decoded = TAGS.get(tag, tag)
|
||
|
ret[decoded] = value
|
||
|
return ret
|
||
|
|
||
|
def main():
|
||
|
|
||
|
print('Sort Pics Scripty\n')
|
||
|
|
||
|
if len(sys.argv) < 2:
|
||
|
print('ERROR: please provide a destination path (directory)')
|
||
|
return -1
|
||
|
|
||
|
dest_dir = sys.argv[1]
|
||
|
if not os.path.exists(dest_dir):
|
||
|
print('ERROR: the provided destination path does not exist')
|
||
|
return -1
|
||
|
|
||
|
# Traverse the root path looking for all JPEGs
|
||
|
file_list = []
|
||
|
for dirpath, dirnames, filenames in os.walk(SOURCE_DIR):
|
||
|
file_list.extend([os.path.join(dirpath, filename) for filename in filenames
|
||
|
if os.path.splitext(filename)[1].lower() in ['.jpg', '.jpeg']])
|
||
|
|
||
|
total = len(file_list)
|
||
|
print('Total: {:d}\n'.format(total))
|
||
|
|
||
|
# ~ print(file_list[0])
|
||
|
# ~ tags = get_exif(file_list[0])
|
||
|
# ~ pp = pprint.PrettyPrinter(width=41, compact=True)
|
||
|
# ~ print()
|
||
|
# ~ pp.pprint(tags)
|
||
|
# ~ return 0
|
||
|
|
||
|
# Iterate over all the JPEGS
|
||
|
processed = 0
|
||
|
for image_path in file_list:
|
||
|
|
||
|
# Read EXIF tag from image and parse out the "DateTime" tag
|
||
|
tags = get_exif(image_path)
|
||
|
dt = datetime.datetime.strptime(tags['DateTime'], DT_FMT)
|
||
|
|
||
|
# Build destination path using year and date from "DateTime" tag
|
||
|
dest_path = os.path.join(dest_dir, '{:04}'.format(dt.year),
|
||
|
'{:02}'.format(dt.month))
|
||
|
|
||
|
# Create destination path if it doesn't already exist
|
||
|
if not os.path.exists(dest_path):
|
||
|
os.makedirs(dest_path)
|
||
|
|
||
|
# Grab filename and copy JPEG file to its new destination
|
||
|
filename = os.path.basename(image_path)
|
||
|
shutil.copyfile(image_path, os.path.join(dest_path, filename))
|
||
|
|
||
|
# Print out status
|
||
|
processed += 1
|
||
|
percent_done = (float(processed) / total) * 100
|
||
|
status = 'Processing {:4d} of {:4d} -- {:.2f}% '\
|
||
|
.format(processed, total, percent_done)
|
||
|
|
||
|
print('\r', end='')
|
||
|
print(status, end='')
|
||
|
|
||
|
print('\n\n')
|
||
|
|
||
|
if __name__ == '__main__':
|
||
|
sys.exit(main())
|
||
Adding sort_pics.py script.