Skip to content

Instantly share code, notes, and snippets.

@fcrespo82
Forked from cliss/organize-photos.py
Last active January 3, 2016 07:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fcrespo82/8429020 to your computer and use it in GitHub Desktop.
Save fcrespo82/8429020 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
import sys
import os, shutil
import subprocess
import os.path
from datetime import datetime
######################## Functions #########################
def photoDate(f):
"Return the date/time on which the given photo was taken."
cDate = subprocess.check_output(['sips', '-g', 'creation', f])
cDate = cDate.split('\n')[1].lstrip().split(': ')[1]
return datetime.strptime(cDate, "%Y:%m:%d %H:%M:%S")
def add_to_dict(dict, date):
key = str(date.year) + "_" + str(date.month)
if not dates.has_key(key):
dates[key] = 1
else:
dates[key] += 1
def progress_bar(total, value):
if value > total:
value = total
multiplier = 60.0/total
print("[{}{}]".format("#"*int(value*multiplier), "-"*int((total-value)*multiplier)))
def print_table(dates, total):
clear()
processed = 0
print("Total = {}".format(total))
print("Processed")
print("| {:^6} | {:^7} | {:^8} |".format("Year", "Month", "Photos"))
for key in sorted(dates):
processed += dates[key]
print("| {:^6} | {:^7} | {:^8} |".format(key.split("_")[0], key.split("_")[1], str(dates[key])))
print("Remaining = {}".format(total - processed))
progress_bar(total, processed)
class clear:
def __call__(self):
import os
if os.name==('ce','nt','dos'): os.system('cls')
elif os.name=='posix': os.system('clear')
else: print('\n'*120)
def __neg__(self): self()
def __repr__(self):
self();return ''
clear=clear()
###################### Main program ########################
# Where the photos are and where they're going.
sourceDir = os.environ['HOME'] + '/Pictures/iPhone Incoming'
destDir = os.environ['HOME'] + '/Pictures/iPhone'
errorDir = destDir + '/Unsorted/'
# The format for the new file names.
fmt = "%Y-%m-%d %H-%M-%S"
# The problem files.
problems = []
# Get all the JPEGs in the source folder.
photos = os.listdir(sourceDir)
photos = [ x for x in photos if x[-4:] == '.jpg' or x[-4:] == '.JPG' ]
# Prepare to output as processing occurs
lastMonth = 0
lastYear = 0
# Create the destination folder if necessary
if not os.path.exists(destDir):
os.makedirs(destDir)
if not os.path.exists(errorDir):
os.makedirs(errorDir)
# Copy photos into year and month subfolders. Name the copies according to
# their timestamps. If more than one photo has the same timestamp, add
# suffixes 'a', 'b', etc. to the names.
dates = {}
for photo in photos:
# print "Processing %s..." % photo
original = sourceDir + '/' + photo
suffix = 'a'
try:
pDate = photoDate(original)
yr = pDate.year
mo = pDate.month
add_to_dict(dates, pDate)
print_table(dates, len(photos))
newname = pDate.strftime(fmt)
thisDestDir = destDir + '/%04d/%02d' % (yr, mo)
if not os.path.exists(thisDestDir):
os.makedirs(thisDestDir)
duplicate = thisDestDir + '/%s.jpg' % (newname)
while os.path.exists(duplicate):
newname = pDate.strftime(fmt) + suffix
duplicate = destDir + '/%04d/%02d/%s.jpg' % (yr, mo, newname)
suffix = chr(ord(suffix) + 1)
shutil.copy2(original, duplicate)
except Exception:
shutil.copy2(original, errorDir + photo)
problems.append(photo)
except:
sys.exit("Execution stopped.")
# Report the problem files, if any.
if len(problems) > 0:
print "\nProblem files:"
print "\n".join(problems)
print "These can be found in: %s" % errorDir
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment