diff options
| author | Guilhem Moulin <guilhem@fripost.org> | 2023-09-28 14:51:35 +0200 | 
|---|---|---|
| committer | Guilhem Moulin <guilhem@fripost.org> | 2023-09-28 15:19:01 +0200 | 
| commit | d068cc2a1058ba23515593a6e2fb8bd178946f5d (patch) | |
| tree | a522fea2d6ad4fb69d549f7f9b0e223ab1220a12 | |
| parent | b5c5e586bf27214aa68dcee20c610e00f2b9c745 (diff) | |
Add option --observation-file to choose a custom observation file name.
(Relative to project home.)  Format is derived from its extension when
possible.
| -rwxr-xr-x | gis-observation-map | 59 | 
1 files changed, 50 insertions, 9 deletions
| diff --git a/gis-observation-map b/gis-observation-map index d7dc03a..dd8f5fe 100755 --- a/gis-observation-map +++ b/gis-observation-map @@ -95,9 +95,12 @@ parser_geom.add_argument('--point', nargs='*', metavar='X,Y', default=[],      help=f'Coordinates of interest (in {target_srs.GetName()})')  parser_geom.add_argument('--margin', metavar='N', type=int,      help='Margin (in meters) around geometry envelopes') -parser.add_argument('--observation-format', metavar='FORMAT', default='GPKG', -    help='Format for the observation file (default: %(default)s)') -parser.add_argument('--observation-style', default=config['QGIS']['observation-style'], metavar='STYLE_FILE', type=ePath, +parser_obs = parser.add_argument_group('Observation file') +parser_obs.add_argument('--observation-file', type=Path, metavar='NAME', +    help='Observation file name relative to --project-home') +parser_obs.add_argument('--observation-format', metavar='FORMAT', +    help='Format for the observation file') +parser_obs.add_argument('--observation-style', default=config['QGIS']['observation-style'], metavar='STYLE_FILE', type=ePath,      help='QGIS Layer Style File (*.qml) to apply to the observation layer (default: %(default)s)')  parser_filter = parser.add_argument_group('Search filter')  parser_filter.add_argument('--data-provider', nargs='*', metavar='IDENTIFIER', default=[], @@ -134,6 +137,9 @@ if args.project_home is not None and args.project_name is not None:      else:          raise Exception('Invalid CRS') +    if args.observation_file is None: +        args.observation_file = Path('observations') +  elif args.project_home is None or args.project_name is None:      parser.print_usage()      exit(1) @@ -420,11 +426,10 @@ def getObservations(taxonLists, taxonRedlistCategories, searchFilter):      if 'crs' not in obs.keys():          print('WARN: GeoJSON output lacks CRS', file=sys.stderr) -    layername = 'Observations'      if obs['type'] == 'FeatureCollection' and 'features' in obs.keys() and type(obs['features']) == list:          print(f'{len(obs["features"])} observations found', file=sys.stderr)          if 'name' not in obs.keys() or obs['name'] is None: -            obs['name'] = layername +            obs['name'] = 'Observations'          for feat in obs['features']:              if (type(feat) != dict or 'type' not in feat.keys() or feat['type'] != 'Feature'                      or 'properties' not in feat.keys() or type(feat['properties']) != dict): @@ -449,9 +454,47 @@ def getObservations(taxonLists, taxonRedlistCategories, searchFilter):                      print(f'WARN: #{tid} {k}: {properties[k]} → {v}', file=sys.stderr)                  properties[k] = v -    drv = ogr.GetDriverByName(args.observation_format) +    if args.observation_file.is_absolute(): +        path = args.observation_file +    elif args.project_home is None: +        path = args.observation_file.expanduser() +    else: +        path = args.project_home.joinpath(args.observation_file) + +    drv = None +    suffix = path.suffix +    if suffix is not None and suffix != '' and suffix != '.': +        # try to infer format from extension +        for i in range(ogr.GetDriverCount()): +            drv2 = ogr.GetDriver(i) +            if drv2 is None: +                continue +            v = drv2.GetMetadataItem(gdal.DMD_EXTENSIONS) +            if v is None: +                continue +            if suffix.removeprefix('.') in v.split(' '): +                drv = drv2 +                break +    if drv is None: +        if args.observation_format is None: +            observation_format = 'GPKG' +        else: +            observation_format = args.observation_format +        drv = ogr.GetDriverByName(observation_format) +        if drv is None: +            raise Exception(f'Invalid format {observation_format}') +        suffixes = drv.GetMetadataItem(gdal.DMD_EXTENSIONS).split(' ') +        if len(suffixes) < 1 or suffixes[0] == '': +            raise Exception(f'Invalid format {observation_format}') +        if suffix is not None and suffix != '' and suffix != '.': +            print(f'WARN: unknown extension "{suffix}", appending ".{suffixes[0]}"', file=sys.stderr) +        suffix += '.' + suffixes[0] +        path = path.with_suffix(suffix) + +    if args.observation_format is not None and drv.name.lower() != args.observation_format.lower(): +        print(f'WARN: overwriting observation file format to {drv.name}', file=sys.stderr) +      if drv.name == geojson_drv.name: -        path = args.project_home.joinpath(layername.lower() + '.geojson')          with path.open(mode='w') as fp:              json.dump(obs, fp, indent=2, ensure_ascii=False)      else: @@ -459,8 +502,6 @@ def getObservations(taxonLists, taxonRedlistCategories, searchFilter):              json.dump(obs, fp)              fp.flush() -            suffix = drv.GetMetadataItem(gdal.DMD_EXTENSIONS).split(' ')[0] -            path = args.project_home.joinpath(layername.lower()).with_suffix('.' + suffix)              gdal.VectorTranslate(path.as_posix(), fp.name, format=drv.name, reproject=True, dstSRS=target_srs)      obs = None | 
