dotfiles/config/scripts/picture_name_date

56 lines
1.7 KiB
Plaintext
Raw Normal View History

2021-06-13 11:49:21 +02:00
#!/usr/bin/env python3
2019-08-04 19:05:57 +02:00
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
2021-06-13 11:49:21 +02:00
EXTENSION_PATTERN = re.compile(r"\.JPE?G", re.I)
COMMON_PATTERN = re.compile(r"(IMG|DSC[NF]?|100|P10|f|t)_?\d+", re.I)
EXIF_TAG_NAME = "DateTimeOriginal"
EXIF_TAG_ID = list(PIL.ExifTags.TAGS.keys())[
list(PIL.ExifTags.TAGS.values()).index(EXIF_TAG_NAME)
]
EXIF_DATE_FORMAT = "%Y:%m:%d %H:%M:%S"
2019-08-04 19:05:57 +02:00
2021-06-13 11:49:21 +02:00
def get_pictures(directory: str = ".", skip_renamed: bool = True) -> typing.Generator:
2019-08-04 19:05:57 +02:00
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)
2021-06-13 11:49:21 +02:00
new_name = date.isoformat().replace(":", "-") + ".jpg" # For NTFS
2020-03-12 17:56:10 +01:00
print(full_path, new_name)
2021-06-13 11:49:21 +02:00
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()