yrasdasda

This commit is contained in:
Geoffrey Frogeye 2022-06-09 18:42:02 +02:00
parent 1a8d1db86c
commit 95faa0c0ff
4 changed files with 274 additions and 25 deletions

View file

@ -1,20 +1,22 @@
#!/usr/bin/env python3
import argparse
import datetime
import logging
import os
import re
import typing
import datetime
import PIL.ExifTags
import PIL.Image
import coloredlogs
import exifread
import progressbar
EXTENSION_PATTERN = re.compile(r"\.JPE?G", re.I)
log = logging.getLogger(__name__)
coloredlogs.install(level="DEBUG", fmt="%(levelname)s %(message)s", logger=log)
EXTENSION_PATTERN = re.compile(r"\.(JPE?G|DNG)", 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_TAG_ID = 0x9003 # DateTimeOriginal
EXIF_DATE_FORMAT = "%Y:%m:%d %H:%M:%S"
@ -23,7 +25,6 @@ def get_pictures(directory: str = ".", skip_renamed: bool = True) -> typing.Gene
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:
@ -33,23 +34,85 @@ def get_pictures(directory: str = ".", skip_renamed: bool = True) -> typing.Gene
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)
def main(args: argparse.Namespace) -> None:
log.warning("Counting files...")
kwargs = {"directory": args.dir, "skip_renamed": args.skip_renamed}
log.warning("Processing files...")
if args.hide_bar:
iterator = get_pictures(**kwargs)
else:
nb_imgs = len(list(get_pictures(**kwargs)))
iterator = progressbar.progressbar(get_pictures(**kwargs), 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]
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
img.close()
# Find date
with open(full_path, 'rb') as fd:
exif_data = exifread.process_file(fd)
if not exif_data:
log.warning(f"{full_path} does not have EXIF data")
for ifd_tag in exif_data.values():
if ifd_tag.tag == EXIF_TAG_ID:
date_raw = ifd_tag.values
break
else:
log.warning(f"{full_path} does not have required EXIF tag")
continue
date = datetime.datetime.strptime(date_raw, EXIF_DATE_FORMAT)
# Determine new filename
ext = os.path.splitext(full_path)[1].lower()
if ext == '.jpeg':
ext = '.jpg'
new_name = date.isoformat().replace(":", "-").replace("T", "_")
# First substitution is to allow images being sent to a NTFS filesystem
# Second substitution is for esthetics
new_path = os.path.join(args.dir, f"{new_name}{ext}")
# TODO Allow keeping image in same folder
i = 0
while os.path.exists(new_path):
if full_path == new_path:
break
log.debug(f"{full_path} already exists, incrementing")
i += 1
new_path = os.path.join(args.dir, f"{new_name}_{i}{ext}")
# Rename file
if full_path == new_path:
log.debug(f"{full_path} already at required filename")
continue
log.info(f"{full_path} →\t{new_path}")
if os.path.exists(new_path):
raise FileExistsError(f"Won't overwrite {new_path}")
if not args.dry:
os.rename(full_path, new_path)
if __name__ == "__main__":
# TODO Arguments parsing
main()
parser = argparse.ArgumentParser(description="Rename images based on their dates")
parser.add_argument(
"dir",
metavar="DIRECTORY",
type=str,
default=".",
nargs="?",
help="Directory containing the pictures",
)
parser.add_argument(
"-d",
"--dry",
action="store_true",
help="Do not actually rename, just show old and new path",
)
parser.add_argument(
"-s",
"--skip-renamed",
action="store_true",
help="Skip images whose filename doesn't match usual camera output filenames.",
)
parser.add_argument(
"-b",
"--hide-bar",
action="store_true",
help="Do not show a progress bar. Also skip counting images",
)
args = parser.parse_args()
main(args)