Created
August 24, 2016 05:37
-
-
Save msharp/7830adae52292c1bbf5eae37b467665c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
############################# | |
# | |
# Appends the camera model, | |
# extracted from the EXIF data | |
# to the file name. | |
# | |
# RAW file support comes via | |
# a Perl command-line tool | |
# called `exiftool` | |
# | |
############################# | |
import sys, os, re | |
import exifread | |
from subprocess import check_output | |
def new_file_name(filename, camera_model): | |
if re.match(r'.*{}'.format(camera_model), filename): | |
return filename | |
else: | |
f, ext = os.path.splitext(filename) | |
return "{0}.{1}{2}".format(f, camera_model, ext) | |
def model_cleanup(s): | |
s = str(s) | |
s = s.replace("FinePix",'') | |
return s.strip() | |
def get_raw_exif(f): | |
# `exiftool` from http://www.sno.phy.queensu.ca/~phil/exiftool/ | |
exif = check_output(["exiftool", f]) | |
exif = [r.split(":") for r in exif.split("\n")] | |
exif = [(v[0].strip(), v[1].strip()) for v in exif if len(v) > 1] | |
return dict(exif) | |
########### | |
if len(sys.argv) > 1: | |
image_dir = os.path.abspath(sys.argv[1].strip()) | |
else: | |
image_dir = os.path.abspath(os.path.dirname(__file__)) | |
files = [(f, image_dir, os.path.join(image_dir, f)) | |
for f in os.listdir(image_dir) | |
if os.path.isfile(os.path.join(image_dir, f))] | |
for f in files: | |
p, ext = os.path.splitext(f[0]) | |
model = None | |
try: | |
if ext == '.jpg': | |
imgf = open(f[2], 'rb') | |
exif = exifread.process_file(imgf) | |
model = model_cleanup(exif['Image Model']) | |
else: # if raw | |
exif = get_raw_exif(f[2]) | |
model = model_cleanup(exif['Camera Model Name']) | |
except: | |
print("couldn't read EXIF data from {}".format(f[2])) | |
pass | |
if model and not re.match(r'.*{}'.format(model), f[0]): | |
new_name = os.path.join(f[1], new_file_name(f[0], model)) | |
print("renaming {0} to {1}".format(f[2], new_name)) | |
os.rename(f[2], new_name) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment