Exemplo n.º 1
0
def get_info_yandex(latitude, longitude):
    items = {}
    query = "{0}?format=json&geocode={1},{2}".format(yandex_geocoder,
                                                     longitude, latitude)

    try:
        result = request_get(query)
    except ConnectionError as errno:
        trace.error(" ".join(("Connection error:", str(errno))))
        return items
    except Timeout as errno:
        trace.error(" ".join(("Connection timeoute exceed:", str(errno))))
        return items
    except HTTPError as errno:
        trace.error(" ".join(("Invalid HTTP response:", str(errno))))
        return items
    except RequestException as errno:
        trace.error('Exception: {0}'.format(errno))
        return items

    core_dic = json_loads(result.text)
    try:
        for feature_member in core_dic['response']['GeoObjectCollection'][
                'featureMember']:
            try:
                kind = feature_member['GeoObject']['metaDataProperty'][
                    'GeocoderMetaData']['kind']
                items[kind] = feature_member['GeoObject']['name']
            except KeyError as errno:
                trace.warning("Invalid key: {0}".format(errno))
    except KeyError as errno:
        trace.warning("Invalid key: {0}".format(errno))
        return items

    return items
Exemplo n.º 2
0
def get_info_yandex(latitude, longitude):
    items = {}
    query = "{0}?format=json&geocode={1},{2}".format(yandex_geocoder, longitude, latitude)

    try:
        result = request_get(query)
    except ConnectionError as errno:
        trace.error(" ".join(("Connection error:", str(errno))))
        return items
    except Timeout as errno:
        trace.error(" ".join(("Connection timeoute exceed:", str(errno))))
        return items
    except HTTPError as errno:
        trace.error(" ".join(("Invalid HTTP response:", str(errno))))
        return items
    except RequestException as errno:
        trace.error('Exception: {0}'.format(errno))
        return items

    core_dic = json_loads(result.text)
    try:
        for feature_member in core_dic['response']['GeoObjectCollection']['featureMember']:
            try:
                kind = feature_member['GeoObject']['metaDataProperty']['GeocoderMetaData']['kind']
                items[kind] = feature_member['GeoObject']['name']
            except KeyError as errno:
                trace.warning("Invalid key: {0}".format(errno))
    except KeyError as errno:
        trace.warning("Invalid key: {0}".format(errno))
        return items

    return items
    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)