/
photolib.py
executable file
·177 lines (135 loc) · 5.16 KB
/
photolib.py
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
173
174
175
176
177
#!/usr/bin/env python3
import argparse
import datetime
import filetype
import os
import piexif
import plistlib
import shutil
import sys
VERBOSE = False
def verbose_log(*args, **kwargs):
global VERBOSE
if VERBOSE:
print(*args, **kwargs)
# thanks StackOverflow!
def remove_prefix(text, prefix):
if text.startswith(prefix):
return text[len(prefix):]
return text
def create_destination_dir(path):
if not os.path.exists(path):
os.makedirs(path)
def load_album_data(path):
with open(os.path.join(path, "AlbumData.xml"), "rb") as f:
return plistlib.load(f)
def album_path_prefx(album_data):
# iPhoto stores images with full pathnames, which is meaningless
# if the album is ever moved, but handily stores what it thinks
# the root directory of the album is. Bizarre.
return album_data["Archive Path"] + os.sep
def get_album_info(album_data, skip_albums):
path_prefix = album_path_prefx(album_data)
# Album list and file paths out to the 'albums.txt' file
d = {}
for album in album_data["List of Albums"]:
name = album["AlbumName"]
if name in skip_albums:
continue
d[name] = []
for key in album["KeyList"]:
pic = album_data["Master Image List"][key]
path = remove_prefix(pic["ImagePath"], path_prefix)
d[name].append(path)
return d
def dump_album_info(dest, album_info):
create_destination_dir(dest)
with open(os.path.join(dest, "albums.txt"), "w") as f:
for key in sorted(album_info.keys()):
print(key, file=f)
for item in sorted(album_info[key]):
print(" ", item, file=f)
print("", file=f)
def set_exif_date(path, date):
if filetype.guess(path) != filetype.get_type("image/jpeg"):
return
tags = piexif.load(path)
datestr = date.strftime('%Y:%m:%d %H:%M:%S')
tags['Exif'][piexif.ExifIFD.DateTimeDigitized] = datestr
tags['Exif'][piexif.ExifIFD.DateTimeOriginal] = datestr
piexif.insert(piexif.dump(tags), path)
def copy_photos(source, dest, album_data):
path_prefix = album_path_prefx(album_data)
i = {}
for pic in album_data["Master Image List"].values():
path = remove_prefix(pic["ImagePath"], path_prefix)
imagesrc = os.path.join(source, path)
# A bunch of the pictures in the master image list appear to be
# duplicated, and a swath of them had broken pathnames. I just
# skip them here, since it doesn't look like they matter. Use
# verbose logging to find things if you can't figure out
# why something important vanished/wasn't copied.
if not os.path.exists(imagesrc):
verbose_log("Not found:", path)
continue
# pathname wrangling
imagedst = os.path.join(dest, path)
dstdir = os.path.dirname(imagedst)
filename = os.path.basename(imagedst)
# copy the file
create_destination_dir(dstdir)
shutil.copyfile(imagesrc, imagedst)
# exif date
date = datetime.datetime.fromtimestamp(pic["DateAsTimerInterval"] + 978307200); # Cocoa epoch
set_exif_date(imagedst, date)
# save captions and comments to the index table
d = os.path.dirname(path)
if not d in i.keys():
i[d] = {}
i[d][filename] = {}
i[d][filename]["Date"] = date
i[d][filename]["Caption"] = pic["Caption"]
i[d][filename]["Comment"] = pic["Comment"]
# write out indices
for d, index in i.items():
with open(os.path.join(dest, d, "index.txt"), "w") as f:
for filename in sorted(index.keys()):
print(filename, file=f)
caption = index[filename]["Caption"]
comment = index[filename]["Comment"]
print(" ", index[filename]["Date"], file=f)
if caption:
print(" ", caption, file=f)
if comment:
print(" ", comment, file=f)
print("", file=f)
def process_arguments(argv):
"""Returns processed arguments."""
parser = argparse.ArgumentParser(
description='Extract information and photos from ancient iPhoto libraries.')
parser.add_argument('source', help='bundle directory of the photo library source')
parser.add_argument('dest', help='directory you want the results to go in')
parser.add_argument('--verbose', '-v', action='store_true', help='enable verbose logging')
args = parser.parse_args(argv)
return args
def main(argv=None):
global VERBOSE
# These are default/builtin iPhoto album names that don't contain
# meaningful information for us. Skip 'em so they don't end up in
# the albums index.
skip_albums = [
"Photos",
"Last 12 Months",
"Last Import",
"Flagged"
]
args = process_arguments(argv)
VERBOSE = args.verbose
album_data = load_album_data(args.source)
album_info = get_album_info(album_data, skip_albums)
dump_album_info(args.dest, album_info)
copy_photos(args.source, args.dest, album_data)
return 0
if __name__ == '__main__':
status = main()
sys.exit(status)