dotfiles/config/scripts/picture_name_date

56 lines
1.7 KiB
Plaintext
Raw Permalink Normal View History

2019-08-04 19:05:57 +02:00
#!/usr/bin/env python
import os
import re
import typing
2020-03-12 17:56:10 +01:00
import datetime
2019-08-04 19:05:57 +02:00
import PIL.ExifTags
import PIL.Image
import progressbar
EXTENSION_PATTERN = re.compile(r'\.JPE?G', re.I)
2020-03-12 17:56:10 +01:00
COMMON_PATTERN = re.compile(r'(IMG|DSC[NF]?|100|P10|f|t)_?\d+', re.I)
2019-08-04 19:05:57 +02:00
EXIF_TAG_NAME = 'DateTimeOriginal'
EXIF_TAG_ID = list(PIL.ExifTags.TAGS.keys())[list(
PIL.ExifTags.TAGS.values()).index(EXIF_TAG_NAME)]
2020-03-12 17:56:10 +01:00
EXIF_DATE_FORMAT = '%Y:%m:%d %H:%M:%S'
2019-08-04 19:05:57 +02:00
def get_pictures(directory: str = ".", skip_renamed: bool = True) \
-> typing.Generator:
for root, _, files in os.walk(directory):
for filename in files:
filename_trunk, extension = os.path.splitext(filename)
# if extension.upper() not in ('.JPEG', '.JPG'):
if not re.match(EXTENSION_PATTERN, extension):
continue
if skip_renamed:
if not re.match(COMMON_PATTERN, filename_trunk):
continue
full_path = os.path.join(root, filename)
yield full_path
def main() -> None:
print("Counting files...")
nb_imgs = len(list(get_pictures()))
print("Processing files...")
iterator = progressbar.progressbar(get_pictures(), max_value=nb_imgs)
for full_path in iterator:
img = PIL.Image.open(full_path)
exif_data = img._getexif()
if exif_data and EXIF_TAG_ID in exif_data:
date_raw = exif_data[EXIF_TAG_ID]
2020-03-12 17:56:10 +01:00
date = datetime.datetime.strptime(date_raw, EXIF_DATE_FORMAT)
new_name = date.isoformat().replace(':', '-') + '.jpg' # For NTFS
print(full_path, new_name)
os.rename(full_path, new_name) # TODO FOLDER
2019-08-04 19:05:57 +02:00
img.close()
if __name__ == "__main__":
# TODO Arguments parsing
main()