def get_formatted_saved_iptc(self):
        photo = self.photo_for_analysis[self.current_photo_ix]
        saved_address_info = []
        saved_keywords = []
        try:
            for key, item in et.get_data_from_image(image=photo, option="-iptc:all")["IPTC"].items():
                if key == "Keywords":
                    # Exiftool can return list of keywords or one keyword as string
                    # We should convert this string to list
                    if type(item) is str:
                        saved_keywords.append(item)
                    else:
                        saved_keywords = item
                elif key in iptc_address_tags:
                    saved_address_info.append(item)
        except KeyError:
            pass

        return """{0}
  {1}:
    {2}
  {3}:
    {4}""".format(get_name("saved_iptc_tags"),
                     get_name("address_info"),
                     "\n    ".join(saved_address_info) if saved_address_info else get_name("empty"),
                     get_name("keywords"),
                     "\n    ".join(saved_keywords) if saved_keywords else get_name("empty"))
Exemplo n.º 2
0
    def get_formatted_saved_iptc(self):
        photo = self.photo_for_analysis[self.current_photo_ix]
        saved_address_info = []
        saved_keywords = []
        try:
            for key, item in et.get_data_from_image(image=photo, option="-iptc:all")["IPTC"].items():
                if key == "Keywords":
                    # Exiftool can return list of keywords or one keyword as string
                    # We should convert this string to list
                    if type(item) is str:
                        saved_keywords.append(item)
                    else:
                        saved_keywords = item
                elif key in iptc_address_tags:
                    saved_address_info.append(item)
        except KeyError:
            pass

        return """{0}
  {1}:
    {2}
  {3}:
    {4}""".format(get_name("saved_iptc_tags"),
                     get_name("address_info"),
                     "\n    ".join(saved_address_info) if saved_address_info else get_name("empty"),
                     get_name("keywords"),
                     "\n    ".join(saved_keywords) if saved_keywords else get_name("empty"))
    def cmd_save_photo(self):
        dir_with_photo = filedialog.askdirectory(parent=self.master, title=get_name("dia_save_photo"), initialdir='/')
        if not dir_with_photo:
            return
        if settings["save_photo"]["save_originals"] == "True":
            file_operation = shutil_copy2
        else:
            file_operation = shutil_move

        # Get list of files to save
        pho_for_saving_without_date = []
        ph_for_saving_with_date = []

        if settings["save_photo"]["check_unsorted"] == "True":
            # Check unsorted files
            files = next(os_walk(os_path.join(settings["projects_dir"], dir_unsorted)))[2]
            for file in files:
                if os_path.splitext(file)[-1].lower() in supported_image_ext:
                        found_matching = dt_in_fn_regex.match(file)
                        if found_matching:
                            try:
                                # Convert collected numeric parts into datetime object
                                ph_for_saving_with_date.append([os_path.join(settings["projects_dir"],
                                                                             dir_unsorted,
                                                                             file),
                                                                datetime.strptime(str(found_matching.group(1)),
                                                                                  '%Y-%m-%d_%H-%M-%S'),
                                                                None])
                            except ValueError:
                                continue

        for root, _, files in os_walk(dir_with_photo):
            for file in files:
                if os_path.splitext(file)[-1].lower() in supported_image_ext:
                    try:
                        # Try to find date/time in metadata
                        possible_dt = et.get_data_from_image(os_path.join(root, file),
                                                             "-EXIF:DateTimeOriginal")["EXIF"]["DateTimeOriginal"]
                        # Convert collected numeric parts into datetime object
                        ph_for_saving_with_date.append([os_path.join(root,
                                                                     file),
                                                        datetime.strptime(possible_dt,
                                                                          '%Y:%m:%d %H:%M:%S'),
                                                        None])
                    # If date/time were not found in metadata too
                    except ValueError:
                        pho_for_saving_without_date.append(os_path.join(root, file))
                        continue

        # Connect photo and project basing on date/time
        for project in next(os_walk(settings["projects_dir"]))[1]:
            if not os_path.isfile(os_path.join(settings["projects_dir"], project, project_file)):
                continue

            with open(os_path.join(os_path.join(settings["projects_dir"]),
                                   project,
                                   project_file),
                      encoding='utf-8') as _f:
                pd = json_load(_f)

            # Parse project timeslot
            prj_start = '{0} {1}'.format(pd["timeslot"]["start"]["date"], pd["timeslot"]["start"]["time"])
            prj_start = datetime.strptime(prj_start, "%d.%m.%Y %H:%M")
            prj_finish = '{0} {1}'.format(pd["timeslot"]["finish"]["date"], pd["timeslot"]["finish"]["time"])
            prj_finish = datetime.strptime(prj_finish, "%d.%m.%Y %H:%M")

            for ph in ph_for_saving_with_date:
                if ph[2] is not None:
                    continue

                if prj_start <= ph[1] <= prj_finish:  # If photo date/time in project timeslot
                    ph[2] = os_path.join(settings["projects_dir"], project, dir_source)

        for ph in ph_for_saving_with_date:
            dest_dir = os_path.normpath(ph[2]) if ph[2] is not None else os_path.join(settings["projects_dir"],
                                                                                      dir_unsorted)
            # TODO: file renaming according to template YYYY-MM-DD_HH-MM-SS.ext
            if os_path.split(ph[0])[0] == dest_dir:
                trace.debug("Try to move photo to the same location: {0}".format(ph[0]))
            else:
                trace.debug("Save photo: {0} -> {1}".format(os_path.normpath(ph[0]), dest_dir))
                try:
                    # Copy/move image
                    file_operation(os_path.normpath(ph[0]), dest_dir)
                    # Copy/move XMP file too if it exists
                    if os_path.isfile(os_path.splitext(ph[0])[0] + xmp_ext):
                        file_operation(os_path.splitext(ph[0])[0] + xmp_ext, dest_dir)
                except shutil_Error as e:  # For example, if file already exists in destination directory
                    trace.warning(e)
Exemplo n.º 4
0
    def cmd_save_photo(self):
        dir_with_photo = filedialog.askdirectory(
            parent=self.master,
            title=get_name("dia_save_photo"),
            initialdir='/')
        if not dir_with_photo:
            return
        if settings["save_photo"]["save_originals"] == "True":
            file_operation = shutil_copy2
        else:
            file_operation = shutil_move

        # Get list of files to save
        pho_for_saving_without_date = []
        ph_for_saving_with_date = []

        if settings["save_photo"]["check_unsorted"] == "True":
            # Check unsorted files
            files = next(
                os_walk(os_path.join(settings["projects_dir"],
                                     dir_unsorted)))[2]
            for file in files:
                if os_path.splitext(file)[-1].lower() in supported_image_ext:
                    found_matching = dt_in_fn_regex.match(file)
                    if found_matching:
                        try:
                            # Convert collected numeric parts into datetime object
                            ph_for_saving_with_date.append([
                                os_path.join(settings["projects_dir"],
                                             dir_unsorted, file),
                                datetime.strptime(str(found_matching.group(1)),
                                                  '%Y-%m-%d_%H-%M-%S'), None
                            ])
                        except ValueError:
                            continue

        for root, _, files in os_walk(dir_with_photo):
            for file in files:
                if os_path.splitext(file)[-1].lower() in supported_image_ext:
                    try:
                        # Try to find date/time in metadata
                        possible_dt = et.get_data_from_image(
                            os_path.join(root, file), "-EXIF:DateTimeOriginal"
                        )["EXIF"]["DateTimeOriginal"]
                        # Convert collected numeric parts into datetime object
                        ph_for_saving_with_date.append([
                            os_path.join(root, file),
                            datetime.strptime(possible_dt,
                                              '%Y:%m:%d %H:%M:%S'), None
                        ])
                    # If date/time were not found in metadata too
                    except ValueError:
                        pho_for_saving_without_date.append(
                            os_path.join(root, file))
                        continue

        # Connect photo and project basing on date/time
        for project in next(os_walk(settings["projects_dir"]))[1]:
            if not os_path.isfile(
                    os_path.join(settings["projects_dir"], project,
                                 project_file)):
                continue

            with open(os_path.join(os_path.join(settings["projects_dir"]),
                                   project, project_file),
                      encoding='utf-8') as _f:
                pd = json_load(_f)

            # Parse project timeslot
            prj_start = '{0} {1}'.format(pd["timeslot"]["start"]["date"],
                                         pd["timeslot"]["start"]["time"])
            prj_start = datetime.strptime(prj_start, "%d.%m.%Y %H:%M")
            prj_finish = '{0} {1}'.format(pd["timeslot"]["finish"]["date"],
                                          pd["timeslot"]["finish"]["time"])
            prj_finish = datetime.strptime(prj_finish, "%d.%m.%Y %H:%M")

            for ph in ph_for_saving_with_date:
                if ph[2] is not None:
                    continue

                if prj_start <= ph[
                        1] <= prj_finish:  # If photo date/time in project timeslot
                    ph[2] = os_path.join(settings["projects_dir"], project,
                                         dir_source)

        for ph in ph_for_saving_with_date:
            dest_dir = os_path.normpath(
                ph[2]) if ph[2] is not None else os_path.join(
                    settings["projects_dir"], dir_unsorted)
            # TODO: file renaming according to template YYYY-MM-DD_HH-MM-SS.ext
            if os_path.split(ph[0])[0] == dest_dir:
                trace.debug(
                    "Try to move photo to the same location: {0}".format(
                        ph[0]))
            else:
                trace.debug("Save photo: {0} -> {1}".format(
                    os_path.normpath(ph[0]), dest_dir))
                try:
                    # Copy/move image
                    file_operation(os_path.normpath(ph[0]), dest_dir)
                    # Copy/move XMP file too if it exists
                    if os_path.isfile(os_path.splitext(ph[0])[0] + xmp_ext):
                        file_operation(
                            os_path.splitext(ph[0])[0] + xmp_ext, dest_dir)
                except shutil_Error as e:  # For example, if file already exists in destination directory
                    trace.warning(e)