Пример #1
0
def _show_plt(_plt, save=None):
    if save:
        _plt.savefig(save)
        _plt.close()
        output.success(f'image saved to file "{Path(save).absolute()}"')
    else:
        _plt.show()
Пример #2
0
def pairs_load(repo: Repo, roi_id, reload, quiet, completion_date):
    """ load data into DB """
    # todo convert name to ID
    if completion_date:
        completion_date = parse_to_utc_string(completion_date)
        if completion_date is None:
            raise OCLIException(
                f"Completion date {completion_date} is invalid")

        output.comment(f"loading products up to {completion_date}")
    if not roi_id and not repo.active_roi:
        raise click.BadOptionUsage(
            'roi_id',
            "ROI is required , set active ROI or provide --roi option")
    _id = int(roi_id) if roi_id else int(repo.active_roi)
    # check roi exists

    db = repo.roi.db
    try:
        geometry = db.loc[_id, 'geometry']
    except KeyError:
        raise click.BadOptionUsage('roi_id', f'ROI "{_id}" not found')
    cache_file_name = _cache_pairs_file_name(repo)
    finder_conf = repo.get_config('finder', {}).copy()
    if completion_date:
        finder_conf['completionDate'] = completion_date
    if not quiet:
        output.table(finder_conf.items())
    if quiet:
        d = pairs.load_data(
            geometry,
            reload=reload,
            callback=None,
            finder_conf=finder_conf,
            cache_file_name=cache_file_name,
        )
    else:
        with click.progressbar(length=100,
                               label='Loading sat products') as bar:

            def callback(total, step):
                if bar.length != total:
                    bar.length = total
                bar.update(step)

            d = pairs.load_data(geometry,
                                reload=reload,
                                callback=callback,
                                finder_conf=finder_conf,
                                cache_file_name=cache_file_name)
    if d.empty:
        raise OCLIException('0 products loaded, product list is not updated!')
    else:
        output.success(f'{len(d)} products loaded into list')
Пример #3
0
def wp_activate(repo: Repo, name: str):
    """ Activate project"""
    # check project exists in the current workspace
    if name.isnumeric():
        name = repo.list_projects()[int(name)]['name']

    ap = repo.get_project_path(name)
    # todo check rw permissions? btw read-only access is valid for some opers
    if not os.path.isdir(ap):
        raise click.FileError(
            ap,
            hint=
            f" try to run 'create -n {name}' to create project in workspace")
    repo.set_config('active_project', name, autosave=False)
    repo.read_project()
    repo.save_main(
    )  # save only main to prevent project settings to be overridden
    output.success(f'current active project is "{name}" ({ap})')
    pass
Пример #4
0
def wp_init(repo: Repo, projects_home, yes):
    """ init tsar cli """
    rc = get_main_rc_name(repo.rc_home)
    # if os.path.isfile(rc):
    if Path(rc).is_file() and not yes_or_confirm(
            yes, f'config file "{rc}" exits, override?'):
        return
    dc = default_main_config(repo.rc_home)
    if projects_home:
        dc['projects_home'] = projects_home
    _phome = dc['projects_home']
    if Path(_phome).is_dir() and not yes_or_confirm(
            yes, f'Directory "{_phome}" exits, Continue?'):
        return
    os.makedirs(_phome, exist_ok=True)

    with open(rc, 'w') as _f:
        yaml.dump(dc, _f)
    output.success(f"configured project home {rc}")
Пример #5
0
def ai_makecog(repo: Repo, task: Task, roi_id, recipe_path, json_only, quiet,
               no_color, less, zone, kind, source, cos_key, friendly_name,
               print_res, warp_resampleAlg, overview_resampleAlg):
    """    Make COG TIFF from visualized results

    \b
    * to make GeoTIFF from custom ENVI file use --source option with filename of ENVI file (without extension)
    * to override recipe kind, use --kind option,
        example:  making image from 'ai preview --export path/to/envi' file use
         makecog zone --kind Image --source path/to/envi
    * to avoid overriding recipe main results use --cos-key and --friendly-name option
        if --friendly-name starts with '+' value will be used as suffix for friendly_name in GeoJSON
        if --cos-key       starts with '+' value will be used as suffix for COS.ResultKey in GeoJSON

    """
    driver = 'MAKECOG'
    if source:
        try:
            # Only valid ENVI or GeoTiff files are alloed
            str = gdal.Info(source, format='json')
            driver = str['driverShortName']
            if driver not in ['ENVI', 'GTiff']:
                raise OCLIException(
                    f"Unsupported source file type: {str['driverShortName']} ({str['driverLongName']})"
                )
        except Exception as e:
            raise OCLIException(f"Option --source: {e}")
    _recipe = recipe_path if recipe_path else resolve_recipe(
        repo, task, roi_id)
    recipe = Recipe(_recipe)
    kind = kind if kind != 'auto' else recipe.get('type')
    if kind in ['Rvi', 'Image']:
        recipe['type'] = 'Image'
    # log.error(recipe['COS']['ResultKey'])
    if cos_key:
        if cos_key.startswith('+'):
            recipe['COS']['ResultKey'] += cos_key[1:]
        else:
            recipe['COS']['ResultKey'] = cos_key
    if friendly_name:
        if friendly_name.startswith('+'):
            recipe['friendly_name'] += friendly_name[1:]
        else:
            recipe['friendly_name'] = friendly_name
    # log.error(recipe['COS']['ResultKey'])
    # log.error(recipe['friendly_name'])
    filenames = Filenames(zone, recipe)
    if source:
        input_file = source
    else:
        input_file = filenames.pred8c_img
    out_file = filenames.out_tiff
    cog_file = filenames.out_cog_tiff
    check_file = cog_file if json_only else input_file
    if not Path(check_file).is_file():
        raise OCLIException(f'file not found: {check_file}')
    os.makedirs(Path(cog_file).parent, exist_ok=True)
    w = GDALWrap3(recipe, input_file, out_file, cog_file)
    try:
        if not json_only:
            if driver == 'GTiff':
                try:

                    shutil.copy(input_file, cog_file)
                    output.success(f"file {input_file} copied to {cog_file}")
                except Exception as e:
                    raise OCLIException(
                        f'Could not copy  "{input_file}" to "{cog_file}" : {e}'
                    )

            else:
                if not quiet:
                    with pfac(log, total=100,
                              desc='Assembling') as (_, callback):

                        def cb(pct, msg, user_data):
                            _ud = user_data[0]
                            # self.log.debug(f"translaing: {round(pct * 100, 2)}% -{msg}- {user_data} {pct}")
                            # reset counter, this t\callback called from multiple prcesses
                            if pct < 0.01:
                                user_data[0] = 0
                            if user_data[0] == 0 or pct - _ud > 0.10:
                                log.debug(
                                    f"Local translating : {round(pct * 100, 2)}%"
                                )
                                user_data[0] = pct
                            callback(100, pct, 'translating')

                        w.make_cog(cb, warp_resampleAlg, overview_resampleAlg)
                else:
                    w.make_cog(None, warp_resampleAlg, overview_resampleAlg)

        _json = w.make_geo_json()
        _json = _json if no_color else colorful_json(_json)
        if print_res:
            click.echo("\n\n\n")
            if less:
                click.echo_via_pager(_json)
            else:
                click.echo(_json)

    except (RuntimeError, OCLIException) as e:
        raise click.UsageError(
            output.error_style(f"COG-tiff generation failed,reason: {e}"))
    pass