Ejemplo n.º 1
0
def write_new_date(filename: Path, new_date: datetime):
    logging.info('update file ' + str(filename) + ' with ' + str(new_date))
    with open(filename, 'rb') as image_file:
        image = Image(image_file)

    new_date_str = new_date.strftime(DATETIME_STR_FORMAT)

    image.datetime_original = new_date_str
    image.datetime = new_date_str

    with open(filename, 'wb') as new_image_file:
        new_image_file.write(image.get_file())
Ejemplo n.º 2
0
def change_datetimes(image_path, time_delta):
    """Take in image file and time change as a time delta object.
    Change exif datetime, datetime_digitized, and datetime_original
    Save file with updated exif datetimes."""
    # Open image.
    with open(image_path, 'rb') as image_file:
        image = Image(image_file)
    # Generate new datetime.
    old_datetime = datetime.datetime.strptime(image.datetime,
                                              '%Y:%m:%d %H:%M:%S')
    new_datetime = (old_datetime + time_delta).strftime("%Y:%m:%d %H:%M:%S")
    # Replace all exif datetimes with new datetime.
    image.datetime = new_datetime
    image.datetime_digitized = new_datetime
    image.datetime_original = new_datetime
    # Rewrite image file.
    with open(image_path, 'wb') as new_image_file:
        new_image_file.write(image.get_file())
    print(f"{image_path[7::]} datetime fixed!")
def strip_exifdates(myfile, date_now, dryrun):
    """Function to remove known EXIF date data that affects sorting"""
    if dryrun == False:
        local_exceptions = {}
        with open(myfile, "rb") as image_file:
            try:
                my_image = Image(image_file)
            except AssertionError as err:
                exc_type, value, traceback = sys.exc_info()
                local_exceptions[myfile] = exc_type
                logger.exception(
                    f"exif library exception caught with {myfile}",
                    exc_info=True)
                return
            try:
                logger.debug(
                    f"Attempting to modify EXIF datetime for {myfile}")
                logger.debug(f"Before my_image.datetime: {my_image.datetime}")
                my_image.datetime = f"{date_now.year}:{date_now.month}:{date_now.day} {date_now.hour}:{date_now.minute}:{date_now.second}"
                logger.debug(f"After my_image.datetime: {my_image.datetime}")
            except (AttributeError, KeyError) as err:
                exc_type, value, traceback = sys.exc_info()
                local_exceptions[myfile] = exc_type
                logger.exception(
                    f"Exception caught modifying datetime with {myfile}",
                    exc_info=True)
                pass
            try:
                logger.debug(
                    f"Attempting to modify EXIF datetime_original for {myfile}"
                )
                logger.debug(
                    f"Before my_image.datetime_original: {my_image.datetime_original}"
                )
                my_image.datetime_original = f"{date_now.year}:{date_now.month}:{date_now.day} {date_now.hour}:{date_now.minute}:{date_now.second}"
                logger.debug(
                    f"After my_image.datetime_original: {my_image.datetime_original}"
                )
            except (AttributeError, KeyError) as err:
                exc_type, value, traceback = sys.exc_info()
                local_exceptions[myfile] = exc_type
                logger.exception(
                    f"Exception caught modifying datetime_original with {myfile}",
                    exc_info=True)
                pass
            try:
                logger.debug(
                    f"Attempting to modify EXIF datetime_digitized for {myfile}"
                )
                logger.debug(
                    f"Before my_image.datetime_digitized: {my_image.datetime_digitized}"
                )
                my_image.datetime_digitized = f"{date_now.year}:{date_now.month}:{date_now.day} {date_now.hour}:{date_now.minute}:{date_now.second}"
                logger.debug(
                    f"After my_image.datetime_digitized: {my_image.datetime_digitized}"
                )
            except (AttributeError, KeyError) as err:
                exc_type, value, traceback = sys.exc_info()
                local_exceptions[myfile] = exc_type
                logger.exception(
                    f"Exception caught modifying datetime_digitized with {myfile}",
                    exc_info=True)
                pass
            try:
                logger.debug(
                    f"Attempting to modify EXIF gps_datestamp for {myfile}")
                logger.debug(
                    f"Before my_image.gps_datestamp: {my_image.gps_datestamp}")
                my_image.gps_datestamp = f"{date_now.year}:{date_now.month}:{date_now.day}"
                logger.debug(
                    f"After my_image.gps_datestamp: {my_image.gps_datestamp}")
            except (AttributeError, KeyError) as err:
                exc_type, value, traceback = sys.exc_info()
                local_exceptions[myfile] = exc_type
                logger.exception(
                    f"Exception caught modifying gps_datestamp with {myfile}",
                    exc_info=True)
                pass
            with open(myfile, "wb") as new_image_file:
                new_image_file.write(my_image.get_file())
    if dryrun == True:
        print(f"DRYRUN: Would have removed EXIF date data on {myfile}")
    logger.debug(f"Iteration exceptions: {local_exceptions}")
    return local_exceptions
Ejemplo n.º 4
0
def process_one_file(
    in_file: Path, out_file: Path, strategies: List[str], formats: List[str]
):
    if not in_file.is_file():
        return

    if in_file.name.startswith("."):
        return

    if in_file.suffix == ".json":
        return

    print(f"{esc(1)}{esc(96)}{in_file.name}{esc(0)} =>\t", end="")

    date: Optional[datetime] = None
    location: Optional[CoordinatesDMS] = None
    image: Optional[Image] = None

    for strategy in reversed(strategies):
        strategy = strategy.lower()

        if strategy == "exif":
            try:
                with in_file.open("rb") as fo:
                    image = Image(fo)
            except Exception:
                image = None
                continue

            e_date, e_location = get_info_from_exif(image)
            date = e_date or date
            location = e_location or location

        elif strategy == "json":
            j_date, j_location = get_info_from_json(in_file)
            date = j_date or date
            location = j_location or location

        elif strategy == "filename":
            f_date, f_location = get_info_from_filename(in_file, formats)
            date = f_date or date
            location = f_location or location

    if date is None:
        print(f"{esc(91)}no date{esc(0)}, ", end="")
    else:
        print(f"{esc(92)}{date.isoformat()}{esc(0)}, ", end="")
        if image is not None:
            image.datetime = date.strftime(DATETIME_STR_FORMAT)

    if location is None:
        print(f"{esc(91)}no location{esc(0)}")
    else:
        print(f"{esc(92)}{coords_dms2dec(location)}{esc(0)}")
        if image is not None:
            try:
                (
                    (image.gps_latitude, image.gps_latitude_ref),
                    (image.gps_longitude, image.gps_longitude_ref),
                ) = location
            except TypeError:
                pass

    if image is not None:
        out_file.write_bytes(image.get_file())
    else:
        out_file.write_bytes(in_file.read_bytes())

    if date is not None:
        os.utime(out_file, (date.timestamp(), date.timestamp()))
Ejemplo n.º 5
0
def processFile(args):
    argob, path = args
    path = Path(path)
    file_info = {
        "creation": None,
        "file_prefix": "",
        "file_suffix": "",
        "file_content_type": "",
        "old_conflict": "",
        "dtpattern_in_path": False,
        "conflict_count": 0,
        "cleaned_file_name": ""
    }
    creation = None
    image_exif = None
    image_exif_date_error = False
    lower_suffix = path.suffix.lower()
    if lower_suffix in img_suffixes:
        file_info["file_content_type"] = "IMG"
        try:
            with path.open(mode='rb') as f:
                image_exif = Image(f)
        except Exception as exc:
            logger.debug("Exception while reading exif: %s" % exc)
        if not image_exif or not image_exif.has_exif:
            logger.debug("image has no exif data/is not compatible: %s", path)
            image_exif = None
        elif hasattr(image_exif, "datetime"):
            try:
                creation = \
                    dt.strptime(image_exif.datetime, "%Y:%m:%d %H:%M:%S")
            except ValueError:
                logger.warning("Invalid format: %s", image_exif.datetime)
                image_exif_date_error = True
        elif hasattr(image_exif, "datetime_original"):
            try:
                creation = \
                    dt.strptime(
                        image_exif.datetime_original, "%Y:%m:%d %H:%M:%S"
                    )
            except ValueError:
                logger.warning("Invalid format: %s",
                               image_exif.datetime_original)
                image_exif_date_error = True
    elif lower_suffix in mov_suffixes:
        file_info["file_content_type"] = "MOV"
    else:
        if not argob.prune:
            logger.info("unrecognized file: %s", path)
        elif argob.dry_run:
            logger.info("Would remove: %s (unrecognized)", path)
        else:
            path.unlink()
        return 1
    if argob.conflict == "ignore":
        file_info["cleaned_file_name"] = path.stem
    else:
        # find conflict counter and hash
        conflictmatch = extract_conflict_pattern.match(path.stem).groupdict()
        file_info["cleaned_file_name"] = conflictmatch["unrelated"]
        if conflictmatch["conflict_hash"]:
            if argob.conflict == "hash":
                # if hash is found, one conflict is indicated
                file_info["conflict_count"] = 1
            else:
                file_info["cleaned_file_name"] = "%s-%s" % (
                    file_info["cleaned_file_name"],
                    conflictmatch["conflict_hash"])
        # if hash and counter: conflict_count = counter + 1
        # if counter: conflict_count  = counter
        # if hash: conflict_count  = 1
        file_info["conflict_count"] += \
            int(conflictmatch["conflict_counter"] or 0)
    # check and potential extract datetime info from filename
    dtnamematch = extraction_pattern.match(file_info["cleaned_file_name"])
    if dtnamematch:
        dtnamematchg = dtnamematch.groupdict()
        file_info["file_prefix"] = dtnamematchg["prefix"] or ""
        file_info["file_suffix"] = dtnamematchg["suffix"] or ""

        file_info["dtpattern_in_path"] = True

        if not creation:
            logger.debug("extract time from path: %s", path)
            creation = dt(year=int(dtnamematchg["year"]),
                          month=int(dtnamematchg["month"]),
                          day=int(dtnamematchg["day"]),
                          hour=int(dtnamematchg["hour"] or 0),
                          minute=int(dtnamematchg["minute"] or 0),
                          second=int(dtnamematchg["second"] or 0))
    # still no creation time
    if not creation:
        logger.debug("extract time from st_ctime: %s", path)
        creation = dt.fromtimestamp(path.stat().st_ctime)
    file_info["creation"] = creation

    if image_exif_date_error:
        file_info["old_file_hash"] = generate_hash(path)
        if argob.dry_run:
            logger.info("Would fix: %s to %s, of %s", image_exif.datetime,
                        creation.strftime("%Y:%m:%d %H:%M:%S"), path)
        else:
            image_exif.datetime = creation.strftime("%Y:%m:%d %H:%M:%S")
            image_exif.datetime_original = image_exif.datetime
            with path.open(mode='wb') as f:
                f.write(image_exif.get_file())

    file_info["file_hash"] = generate_hash(path)
    if rename_file(argob, path, file_info):
        return 1
    return 0