Beispiel #1
0
 def processor(cm):
     if len(values) == 0:
        bbox = cm.translate(values=[], minimum_xyz=True)
     else:
         bbox = cm.translate(values=values, minimum_xyz=False)
     utils.print_cmd_status('Translating the file by: (%f, %f, %f)' % (bbox[0], bbox[1], bbox[2]))
     return cm
Beispiel #2
0
 def processor(cm):
     vlatest = cityjson.CITYJSON_VERSIONS_SUPPORTED[-1]
     utils.print_cmd_status('Upgrade CityJSON file to v%s' % vlatest)
     re, reasons = cm.upgrade_version(vlatest)
     if (re == False):
         click.echo(click.style("WARNING: %s" % (reasons), fg='red'))
     return cm
Beispiel #3
0
 def processor(cm):
     if folder_schemas is not None:
         if os.path.exists(folder_schemas) == False:
             click.echo(click.style("Folder for schemas unknown. Validation aborted.", fg='red'))
             return cm
         else:
             utils.print_cmd_status('===== Validation (with provided schemas) =====')
     else:
         utils.print_cmd_status('===== Validation (with official CityJSON schemas) =====')
     #-- validate    
     bValid, woWarnings, errors, warnings = cm.validate(skip_schema=skip_schema, folder_schemas=folder_schemas, longerr=long)
     click.echo('=====')
     if bValid == True:
         click.echo(click.style('File is valid', fg='green'))
     else:    
         click.echo(click.style('File is invalid', fg='red'))
     if woWarnings == True:
         click.echo(click.style('File has no warnings', fg='green'))
     else:
         click.echo(click.style('File has warnings', fg='red'))
     if not hide_errors and bValid is False:
         click.echo("--- ERRORS (total = %d) ---" % len(errors))
         for i, e in enumerate(errors):
             click.echo(str(i + 1) + " ==> " + e + "\n")
     if not hide_errors and woWarnings is False:
         click.echo("--- WARNINGS ---")
         for e in warnings:
             click.echo(e)
     click.echo('=====================================')
     return cm
Beispiel #4
0
    def saver(cm):
        output = utils.verify_filename(filename)
        if output['dir']:
            os.makedirs(output['path'], exist_ok=True)
            input_filename = os.path.splitext(os.path.basename(cm.path))[0]
            output['path'] = os.path.join(
                output['path'], '{f}.{ext}'.format(f=input_filename,
                                                   ext='json'))
        else:
            os.makedirs(os.path.dirname(output['path']), exist_ok=True)

        try:
            if "metadata" in cm.j:
                cm.j["metadata"]["fileIdentifier"] = os.path.basename(
                    output['path'])
        except:
            pass

        utils.print_cmd_status("Saving CityJSON to a file %s" % output['path'])
        try:
            fo = click.open_file(output['path'], mode='w')
            if textures:
                cm.copy_textures(textures, output['path'])
            if indent:
                json_str = json.dumps(cm.j, indent="\t")
                fo.write(json_str)
            else:
                json_str = json.dumps(cm.j, separators=(',', ':'))
                fo.write(json_str)
        except IOError as e:
            raise click.ClickException('Invalid output file: %s \n%s' %
                                       (output['path'], e))
Beispiel #5
0
 def processor(cm):
     if (cityjson.MODULE_PYPROJ_AVAILABLE == False):
         str = "Reprojection skipped: Python module 'pyproj' missing (to reproject coordinates)"
         click.echo(click.style(str, fg='red'))
         str = "Install it: https://pypi.org/project/pyproj/"
         click.echo(str)
         return cm
     utils.print_cmd_status('Reproject to EPSG:%d' % epsg)
     if (cm.get_epsg() == None):
         click.echo("WARNING: CityJSON has no EPSG defined, can't be reprojected.")
     else:    
         cm.reproject(epsg)
     return cm
Beispiel #6
0
 def processor(cm):
     utils.print_cmd_status('Subset of CityJSON')
     s = copy.deepcopy(cm)
     if random is not None:
         s = s.get_subset_random(random, exclude=exclude)
         return s
     if len(id) > 0:
         s = s.get_subset_ids(id, exclude=exclude)
     if len(bbox) > 0:
         s = s.get_subset_bbox(bbox, exclude=exclude)
     if cotype is not None:
         s = s.get_subset_cotype(cotype, exclude=exclude)
     return s
Beispiel #7
0
 def exporter(cm):
     output = utils.verify_filename(filename)
     if output['dir']:
         os.makedirs(output['path'], exist_ok=True)
         input_filename = os.path.splitext(os.path.basename(cm.path))[0]
         output['path'] = os.path.join(
             output['path'], '{f}.{ext}'.format(f=input_filename,
                                                ext=format))
     else:
         os.makedirs(os.path.dirname(output['path']), exist_ok=True)
     if format.lower() == 'obj':
         utils.print_cmd_status("Exporting CityJSON to OBJ (%s)" %
                                (output['path']))
         try:
             with click.open_file(output['path'], mode='w') as fo:
                 re = cm.export2obj()
                 fo.write(re.getvalue())
         except IOError as e:
             raise click.ClickException('Invalid output file: "%s".\n%s' %
                                        (output['path'], e))
     elif format.lower() == 'stl':
         utils.print_cmd_status("Exporting CityJSON to STL (%s)" %
                                (output['path']))
         try:
             with click.open_file(output['path'], mode='w') as fo:
                 re = cm.export2stl()
                 fo.write(re.getvalue())
         except IOError as e:
             raise click.ClickException('Invalid output file: "%s".\n%s' %
                                        (output['path'], e))
     elif format.lower() == 'glb':
         fname = os.path.splitext(os.path.basename(output['path']))[0]
         bufferbin = "{}.glb".format(fname)
         binfile = os.path.join(os.path.dirname(output['path']), bufferbin)
         utils.print_cmd_status("Exporting CityJSON to glb %s" % binfile)
         glb = cm.export2gltf()
         # TODO B: how many buffer can there be in the 'buffers'?
         try:
             glb.seek(0)
             with click.open_file(binfile, mode='wb') as bo:
                 bo.write(glb.getvalue())
         except IOError as e:
             raise click.ClickException('Invalid output file: "%s".\n%s' %
                                        (binfile, e))
     elif format.lower() == 'b3dm':
         fname = os.path.splitext(os.path.basename(output['path']))[0]
         b3dmbin = "{}.b3dm".format(fname)
         binfile = os.path.join(os.path.dirname(output['path']), b3dmbin)
         b3dm = cm.export2b3dm()
         utils.print_cmd_status("Exporting CityJSON to b3dm %s" % binfile)
         utils.print_cmd_warning(
             "Although the conversion works, the output is probably incorrect."
         )
         try:
             b3dm.seek(0)
             with click.open_file(binfile, mode='wb') as bo:
                 bo.write(b3dm.getvalue())
         except IOError as e:
             raise click.ClickException('Invalid output file: "%s".\n%s' %
                                        (binfile, e))
Beispiel #8
0
 def processor(cm):
     utils.print_cmd_status('Merging files')
     lsCMs = []
     g = glob.glob(filepattern)
     for i in g:
         try:
             f = click.open_file(i, mode='r', encoding='utf-8-sig')
             lsCMs.append(cityjson.reader(f))
         except ValueError as e:
             raise click.ClickException('%s: "%s".' % (e, input))
         except IOError as e:
             raise click.ClickException('Invalid file: "%s".' % (input))
     if len(lsCMs) == 0:
         click.echo("WARNING: No files to merge.")
     else:
         cm.merge(lsCMs)
     return cm
Beispiel #9
0
def process_pipeline(processors, input, ignore_duplicate_keys):
    extensions = ['.json', '.off', '.poly']  #-- input allowed
    try:
        f = click.open_file(input, mode='r', encoding='utf-8-sig')
        extension = os.path.splitext(input)[1].lower()
        if extension not in extensions:
            raise IOError(
                "File type not supported (only .json, .off, and .poly).")
        #-- OFF file
        if (extension == '.off'):
            utils.print_cmd_status("Converting %s to CityJSON" % (input))
            cm = cityjson.off2cj(f)
        #-- POLY file
        elif (extension == '.poly'):
            utils.print_cmd_status("Converting %s to CityJSON" % (input))
            cm = cityjson.poly2cj(f)
        #-- CityJSON file
        else:
            utils.print_cmd_status("Parsing %s" % (input))
            cm = cityjson.reader(file=f,
                                 ignore_duplicate_keys=ignore_duplicate_keys)
            if not isinstance(cm.get_version(), str):
                str1 = "CityJSON version should be a string 'X.Y' (eg '1.0')"
                raise click.ClickException(str1)
            pattern = re.compile(
                "^(\d\.)(\d)$")  #-- correct pattern for version
            pattern2 = re.compile(
                "^(\d\.)(\d\.)(\d)$")  #-- wrong pattern with X.Y.Z
            if pattern.fullmatch(cm.get_version()) == None:
                if pattern2.fullmatch(cm.get_version()) != None:
                    str1 = "CityJSON version should be only X.Y (eg '1.0') and not X.Y.Z (eg '1.0.1')"
                    raise click.ClickException(str1)
                else:
                    str1 = "CityJSON version is wrongly formatted"
                    raise click.ClickException(str1)
            if (cm.get_version() not in cityjson.CITYJSON_VERSIONS_SUPPORTED):
                allv = ""
                for v in cityjson.CITYJSON_VERSIONS_SUPPORTED:
                    allv = allv + v + "/"
                str1 = "CityJSON version %s not supported (only versions: %s), not every operators will work.\nPerhaps it's time to upgrade cjio? 'pip install cjio -U'" % (
                    cm.get_version(), allv)
                raise click.ClickException(str1)
            elif (cm.get_version() !=
                  cityjson.CITYJSON_VERSIONS_SUPPORTED[-1]):
                str1 = "v%s is not the latest version, and not everything will work.\n" % cm.get_version(
                )
                str1 += "Upgrade the file with 'upgrade_version' command: 'cjio input.json upgrade_version save out.json'"
                click.echo(click.style(str1, fg='red'))

    except ValueError as e:
        raise click.ClickException('%s: "%s".' % (e, input))
    except IOError as e:
        raise click.ClickException('Invalid file: "%s".\n%s' % (input, e))
    for processor in processors:
        cm = processor(cm)
Beispiel #10
0
 def processor(cm):
     utils.print_cmd_status('Remove duplicate vertices')
     cm.remove_duplicate_vertices(precision)
     return cm
Beispiel #11
0
 def processor(cm):
     utils.print_cmd_status('Assign EPSG:%d' % newepsg)
     cm.set_epsg(newepsg)
     return cm
Beispiel #12
0
 def processor(cm):
     utils.print_cmd_status('Remove all textures')
     cm.remove_textures()
     return cm
Beispiel #13
0
 def processor(cm):
     utils.print_cmd_status('Decompressing the CityJSON')
     if (cm.decompress() == False):
         click.echo("File is not compressed, nothing done.")
     return cm
Beispiel #14
0
 def processor(cm):
     utils.print_cmd_status('Compressing the CityJSON (with %d digit)' %
                            digit)
     if cm.compress(digit) == False:
         click.echo("WARNING: CityJSON already compressed.")
     return cm
Beispiel #15
0
 def processor(cm):
     utils.print_cmd_status('Extract LoD:%s' % lod)
     cm.extract_lod(lod)
     return cm
Beispiel #16
0
 def processor(cm):
     utils.print_cmd_status('Locate the textures')
     loc = cm.get_textures_location()
     click.echo(loc)
     return cm
Beispiel #17
0
 def processor(cm):
     utils.print_cmd_status('Clean the file')
     cm.remove_duplicate_vertices(digit)
     cm.remove_orphan_vertices()
     return cm
Beispiel #18
0
 def processor(cm):
     utils.print_cmd_status('Update location of textures')
     cm.update_textures_location(newlocation, relative=relative)
     return cm
Beispiel #19
0
 def processor(cm):
     utils.print_cmd_status('Remove orphan vertices')
     cm.remove_orphan_vertices()
     return cm
Beispiel #20
0
    def processor(cm):
        utils.print_cmd_status('Update the metadata')
        re, errors = cm.update_metadata(overwrite)

        for e in errors:
            utils.print_cmd_warning(e)
Beispiel #21
0
 def processor(cm):
     utils.print_cmd_status('Remove all material')
     cm.remove_materials()
     return cm