-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.py
245 lines (188 loc) · 7.13 KB
/
run.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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import pytz
from datetime import datetime
from dateutil import parser
import os
import sys
import subprocess
import logging
from exif import Image as ExifImage
from tqdm import tqdm
from PIL import Image
from pillow_heif import register_heif_opener
# Ref: https://stackoverflow.com/questions/38537905/set-logging-levels
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.ERROR) # Change logging level to DEBUG for more info.
LOCAL_TIMEZONE = "Asia/Karachi"
DEFAULT_TZ_OFFSET = "+0500"
# for iPhone's .HEIC image files.
register_heif_opener()
# PWD
SOURCE_DIRECTORY = ""
EXIF_DATE_FORMAT = "%Y:%m:%d %H:%M:%S"
EXIF_DATE_FORMAT_TZ = "%Y:%m:%d %H:%M:%S %z"
IMAGE_EXTENSIONS = [
"jpg",
"heic",
]
VIDEO_EXTENSIONS = [
"mp4",
"mov"
]
def main(source_directory):
source_directory = os.path.abspath(source_directory)
logger.info(f"Reading directory: {source_directory}")
for root, subdirs, files in os.walk(source_directory):
logger.info(f"Reading files in directory: {root}")
update_files_stamps(root, files)
def update_files_stamps(root_dir, files):
for file in tqdm(files, desc=f"Files in the directory {root_dir}"):
file = os.path.join(root_dir, file)
logger.debug(f"Checking file {file}...")
if is_image(file):
logger.debug(f"File {file} is an image.")
process_image_file(file)
elif is_video(file):
logger.debug(f"File {file} is a video.")
process_video_file(file)
else:
logger.error(f"Unidentified media file: {file}")
def is_image(file):
return get_extension(file) in IMAGE_EXTENSIONS
def is_video(file):
return get_extension(file) in VIDEO_EXTENSIONS
def get_extension(file: str):
try:
return file.lower().split(".")[1:][-1]
except IndexError:
logger.error(f"Error: no extension found: {file}")
return None
def process_image_file(image_file_path):
if image_file_path.lower().endswith("heic"): # iPhone image
logger.debug(f"Found HEIC image: {image_file_path}")
process_heic_image_file(image_file_path)
else:
logger.debug(f"Found non-HEIC image: {image_file_path}")
process_non_heic_image_file(image_file_path)
def process_heic_image_file(image_file_path):
# TODO: Add timezone support?
image = Image.open(image_file_path)
image.verify()
datetime_str = image.getexif().get(306)
datetime_stamp = datetime.strptime(datetime_str, EXIF_DATE_FORMAT)
update_timestamp(image_file_path, datetime_stamp)
def process_non_heic_image_file(image_file_path):
exif_image = ExifImage(open(image_file_path, "rb"))
if exif_image.has_exif and hasattr(exif_image, "datetime"):
offset = exif_image.get("offset_time", DEFAULT_TZ_OFFSET).replace(":", "")
datetime_str = f"{exif_image.datetime} {offset}"
datetime_stamp = datetime.strptime(datetime_str, EXIF_DATE_FORMAT_TZ)
datetime_stamp = datetime_stamp.astimezone(pytz.timezone(LOCAL_TIMEZONE))
update_timestamp(image_file_path, datetime_stamp)
return
# No exif data, trying other approach.
image = Image.open(image_file_path)
image.verify()
try:
datetime_str = image._getexif()[36867]
datetime_stamp = datetime.strptime(datetime_str, EXIF_DATE_FORMAT)
update_timestamp(image_file_path, datetime_stamp)
return
except (KeyError, IndexError, TypeError):
pass
# Second approach failed, so final attempt. Call the subprocess.
datetime_stamp = _run_exiftool_process(image_file_path, "createdate", is_timestamp=True)
if datetime_stamp:
update_timestamp(image_file_path, datetime_stamp)
else:
logger.error("All methods fail to fetch timestamp for file: {}".format(image_file_path))
def process_video_file(file):
timestamp = read_video_creation_date(file)
update_video_file_metadata(file, timestamp)
update_timestamp(file, timestamp)
def read_video_creation_date(video_path):
"""
Ref: https://stackoverflow.com/questions/60576891/how-to-read-exif-data-of-movies-in-python
"""
return _run_exiftool_process(video_path, "createdate", is_timestamp=True)
def _run_exiftool_process(file_path, required_key, is_timestamp=False):
absolute_path = os.path.join(os.getcwd(), file_path)
process = subprocess.Popen(
["exiftool", f"-{required_key}", absolute_path],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
out, err = process.communicate()
lines = out.decode("utf-8").split("\n")
lines = [line for line in lines if line.strip() != ""]
if len(lines) < 1 or err:
logger.error("Error while running exif tool for {file_path} with getter {required_key}")
logger.error(err)
return None
required_output = str(lines[0].split(" : ")[1].strip())
logger.debug(lines)
if is_timestamp:
datetime_str = required_output
timezone = "0500"
# TODO: fix for -ve timezones
if "+" in datetime_str:
datetime_str_wo_tz, timezone = datetime_str.split("+")
timezone = timezone.replace(":", "")
else:
datetime_str_wo_tz = datetime_str
full_datetime_str = f'{datetime_str_wo_tz} +{timezone}'
logger.debug(f"Date after formatting the timezone info: {full_datetime_str}")
return datetime.strptime(full_datetime_str, EXIF_DATE_FORMAT_TZ)
else:
return required_output
def update_timestamp(file, timestamp):
stats = os.stat(file)
new_access_time = stats.st_atime
new_modified_time = str(timestamp)
new_modified_time_epoch = timestamp.timestamp()
logger.debug(f"Setting access time for file: {file}, to {new_access_time}")
logger.debug(f"Setting modified time for file: {file}, to {new_modified_time}")
os.utime(file, (new_modified_time_epoch, new_modified_time_epoch))
def update_video_file_metadata(file, timestamp):
EXIF_TAGS_TO_UPDATE = [
"modifydate",
"trackcreatedate",
"trackmodifydate",
"mediacreatedate",
"mediamodifydate",
"createdate",
]
DATETIME_FORMAT = "%Y:%m:%d %H:%M:%S"
new_datetime_stamp = timestamp.strftime(DATETIME_FORMAT)
absolute_path = os.path.join(os.getcwd(), file)
process = subprocess.Popen(
[
"exiftool",
*[
f"-{tag}='{new_datetime_stamp}'" for tag in EXIF_TAGS_TO_UPDATE
],
absolute_path,
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
out, err = process.communicate()
output = out.decode("utf-8")
logger.info(f"Updated metdata for file: {file}")
logger.debug(output)
process = subprocess.Popen(
[
"exiftool",
"-delete_original!",
absolute_path,
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
out, err = process.communicate()
output = out.decode("utf-8")
logger.info("Deleted backed-up original file.")
logger.debug(output)
if __name__ == "__main__":
source_directory = sys.argv[1] if len(sys.argv) > 1 else SOURCE_DIRECTORY
main(source_directory)