Exemplo n.º 1
0
    def install(self,
                *,
                gis=None,
                **kwargs):

        """
        Function is used to install the uploaded model package (*.dlpk). Optionally after inferencing
        the necessary information using the model, the model can be uninstalled by uninstall_model()


        ==================     ====================================================================
        **Argument**           **Description**
        ------------------     --------------------------------------------------------------------
        gis                    Optional GIS. The GIS on which this tool runs. If not specified, the active GIS is used.
        ==================     ====================================================================

        :return:
            Path where model is installed

        """
        if self._model_package is False:
            raise RuntimeError("model object should be created from a portal item or a portal url")

        task = "InstallDeepLearningModel"

        gis = _arcgis.env.active_gis if gis is None else gis
        url = gis.properties.helperServices.rasterAnalytics.url
        gptool = _arcgis.gis._GISResource(url, gis)

        params = {}

        if self._model is None:
            raise RuntimeError("For install/uninstall model object should be created from a portal item or portal url")
        else:
            params["modelPackage"] = self._model

        task_url, job_info, job_id = _analysis_job(gptool, task, params)

        job_info = _analysis_job_status(gptool, task_url, job_info)
        job_values = _analysis_job_results(gptool, task_url, job_info, job_id)
        item_properties = {
            "properties": {
                "jobUrl": task_url + '/jobs/' + job_info['jobId'],
                "jobType": "GPServer",
                "jobId": job_info['jobId'],
                "jobStatus": "completed"
            }
        }

        return job_values["installSucceed"]
Exemplo n.º 2
0
    def uninstall(self,
                  *,
                  gis=None,
                  **kwargs):

        """
        Function is used to uninstall the uploaded model package that was installed using the install_model()
        This function will delete the named deep learning model from the server but not the portal item.

        ==================     ====================================================================
        **Argument**           **Description**
        ------------------     --------------------------------------------------------------------
        gis                    Optional GIS. The GIS on which this tool runs. If not specified, the active GIS is used.
        ==================     ====================================================================

        :return:
            itemId of the uninstalled model package item

        """
        if self._model_package is False:
            raise RuntimeError("For install/uninstall model object should be created from a portal item or a portal url")

        task = "UninstallDeepLearningModel"

        gis = _arcgis.env.active_gis if gis is None else gis
        url = gis.properties.helperServices.rasterAnalytics.url
        gptool = _arcgis.gis._GISResource(url, gis)

        params = {}

        if self._model is None:
            raise RuntimeError('model_package cannot be None')
        else:
            params["modelItemId"] = self._model

        task_url, job_info, job_id = _analysis_job(gptool, task, params)

        job_info = _analysis_job_status(gptool, task_url, job_info)
        job_values = _analysis_job_results(gptool, task_url, job_info, job_id)
        item_properties = {
            "properties": {
                "jobUrl": task_url + '/jobs/' + job_info['jobId'],
                "jobType": "GPServer",
                "jobId": job_info['jobId'],
                "jobStatus": "completed"
            }
        }

        return job_values["uninstallSucceed"]
Exemplo n.º 3
0
    def query_info(self,
                   *,
                   gis=None,
                   **kwargs):
        """
        Function is used to extract the deep learning model specific settings from the model package item or model definition file.

        ==================     ====================================================================
        **Argument**           **Description**
        ------------------     --------------------------------------------------------------------
        gis                    Optional GIS. The GIS on which this tool runs. If not specified, the active GIS is used.
        ==================     ====================================================================

        :return:
           The key model information in dictionary format that describes what the settings are essential for this type of deep learning model.
        """


        task = "QueryDeepLearningModelInfo"

        gis = _arcgis.env.active_gis if gis is None else gis
        url = gis.properties.helperServices.rasterAnalytics.url
        gptool = _arcgis.gis._GISResource(url, gis)

        params = {}

        if self._model is None:
            raise RuntimeError('model cannot be None')
        else:
            params["model"] = self._model

        task_url, job_info, job_id = _analysis_job(gptool, task, params)

        job_info = _analysis_job_status(gptool, task_url, job_info)
        job_values = _analysis_job_results(gptool, task_url, job_info, job_id)
        item_properties = {
            "properties": {
                "jobUrl": task_url + '/jobs/' + job_info['jobId'],
                "jobType": "GPServer",
                "jobId": job_info['jobId'],
                "jobStatus": "completed"
            }
        }
        output = job_values["outModelInfo"]
        try:
            dict_output =  _json.loads(output["modelInfo"])
            return dict_output
        except:
            return output
Exemplo n.º 4
0
def list_models(*,
                gis=None,
                **kwargs):
    """
    Function is used to list all the installed deep learning models.

    ==================     ====================================================================
    **Argument**           **Description**
    ------------------     --------------------------------------------------------------------
    gis                    Optional GIS. The GIS on which this tool runs. If not specified, the active GIS is used.
    ==================     ====================================================================

    :return:
        list of deep learning models installed

    """



    task = "ListDeepLearningModels"

    gis = _arcgis.env.active_gis if gis is None else gis
    url = gis.properties.helperServices.rasterAnalytics.url
    gptool = _arcgis.gis._GISResource(url, gis)
    params = {}
    task_url, job_info, job_id = _analysis_job(gptool, task, params)

    job_info = _analysis_job_status(gptool, task_url, job_info)
    job_values = _analysis_job_results(gptool, task_url, job_info, job_id)
    item_properties = {
        "properties": {
            "jobUrl": task_url + '/jobs/' + job_info['jobId'],
            "jobType": "GPServer",
            "jobId": job_info['jobId'],
            "jobStatus": "completed"
        }
    }

    output_model_list = []
    if isinstance(job_values["deepLearningModels"], list) and job_values["deepLearningModels"] is not None:
        for element in job_values["deepLearningModels"]:
            if isinstance(element,dict):
                if "id" in element.keys():
                    item = gis.content.get(element["id"])
                    output_model_list.append(Model(item))
    return output_model_list
Exemplo n.º 5
0
def export_training_data(input_raster,
                         input_class_data=None,
                         chip_format=None,
                         tile_size=None,
                         stride_size=None,
                         metadata_format=None,
                         classvalue_field=None,
                         buffer_radius=None,
                         output_location=None,
                         context=None,
                         input_mask_polygons=None,
                         rotation_angle=0,
                         *,
                         gis=None,
                         **kwargs):

    """
    Function is designed to generate training sample image chips from the input imagery data with
    labeled vector data or classified images. The output of this service tool is the data store string
    where the output image chips, labels and metadata files are going to be stored.

    ==================     ====================================================================
    **Argument**           **Description**
    ------------------     --------------------------------------------------------------------
    input_raster           Required. Raster layer that needs to be exported for training
    ------------------     --------------------------------------------------------------------
    input_class_data       Labeled data, either a feature layer or image layer.
                           Vector inputs should follow a training sample format as
                           generated by the ArcGIS Pro Training Sample Manager.
                           Raster inputs should follow a classified raster format as generated by the Classify Raster tool.
    ------------------     --------------------------------------------------------------------
    chip_format            Optional string. The raster format for the image chip outputs.

                           - TIFF: TIFF format

                           - PNG: PNG format

                           - JPEG: JPEG format

                           - MRF: MRF (Meta Raster Format)
    ------------------     --------------------------------------------------------------------
    tile_size              Optional dictionary. The size of the image chips.

                           Example: {"x": 256, "y": 256}
    ------------------     --------------------------------------------------------------------
    stride_size            Optional dictionary. The distance to move in the X and Y when creating the next image chip.
                           When stride is equal to the tile size, there will be no overlap.
                           When stride is equal to half of the tile size, there will be 50% overlap.

                           Example: {"x": 128, "y": 128}
    ------------------     --------------------------------------------------------------------
    metadata_format        Optional string. The format of the output metadata labels. There are 4 options for output metadata labels for the training data,
                           KITTI Rectangles, PASCAL VOCrectangles, Classified Tiles (a class map) and RCNN_Masks. If your input training sample data
                           is a feature class layer such as building layer or standard classification training sample file,
                           use the KITTI or PASCAL VOC rectangle option.

                           The output metadata is a .txt file or .xml file containing the training sample data contained
                           in the minimum bounding rectangle. The name of the metadata file matches the input source image
                           name. If your input training sample data is a class map, use the Classified Tiles as your output metadata format option.

                           - KITTI_rectangles: The metadata follows the same format as the Karlsruhe Institute of Technology and Toyota
                             Technological Institute (KITTI) Object Detection Evaluation dataset. The KITTI dataset is a vision benchmark suite.
                             This is the default.The label files are plain text files. All values, both numerical or strings, are separated by
                             spaces, and each row corresponds to one object.

                           - PASCAL_VOC_rectangles: The metadata follows the same format as the Pattern Analysis, Statistical Modeling and
                             Computational Learning, Visual Object Classes (PASCAL_VOC) dataset. The PASCAL VOC dataset is a standardized
                             image data set for object class recognition.The label files are XML files and contain information about image name,
                             class value, and bounding box(es).

                           - Classified_Tiles: This option will output one classified image chip per input image chip.
                             No other meta data for each image chip. Only the statistics output has more information on the
                             classes such as class names, class values, and output statistics.

                           - RCNN_Masks: This option will output image chips that have a mask on the areas where the sample exists.
                             The model generates bounding boxes and segmentation masks for each instance of an object in the image.
                             It's based on Feature Pyramid Network (FPN) and a ResNet101 backbone.

                           - Labeled_Tiles : This option will label each output tile with a specific class.
    ------------------     --------------------------------------------------------------------
    classvalue_field       Optional string. Specifies the field which contains the class values. If no field is specified,
                           the system will look for a 'value' or 'classvalue' field. If this feature does
                           not contain a class field, the system will presume all records belong the 1 class.
    ------------------     --------------------------------------------------------------------
    buffer_radius          Optional integer. Specifies a radius for point feature classes to specify training sample area.
    ------------------     --------------------------------------------------------------------
    output_location        This is the output location for training sample data.
                           It can be the server data store path or a shared file system path.

                           Example:

                           Server datastore path -
                            ``/fileShares/deeplearning/rooftoptrainingsamples``
                            ``/rasterStores/rasterstorename/rooftoptrainingsamples``
                            ``/cloudStores/cloudstorename/rooftoptrainingsamples``

                           File share path - 
                            ``\\\\servername\\deeplearning\\rooftoptrainingsamples``
    ------------------     --------------------------------------------------------------------
    context                Optional dictionary. Context contains additional settings that affect task execution.
                           Dictionary can contain value for following keys:

                           - exportAllTiles - Choose if the image chips with overlapped labeled data will be exported.
                             True - Export all the image chips, including those that do not overlap labeled data. 
                             False - Export only the image chips that overlap the labelled data. This is the default.

                           - startIndex - Allows you to set the start index for the sequence of image chips.
                             This lets you append more image chips to an existing sequence. The default value is 0.

                           - cellSize - cell size can be set using this key in context parameter

                           - extent - Sets the processing extent used by the function

                           Setting context parameter will override the values set using arcgis.env 
                           variable for this particular function.(cellSize, extent)

                           eg: {"exportAllTiles" : False, "startIndex": 0 }
    ------------------     --------------------------------------------------------------------
    input_mask_polygons    Optional feature layer. The feature layer that delineates the area where 
                           image chips will be created.
                           Only image chips that fall completely within the polygons will be created.
    ------------------     --------------------------------------------------------------------
    rotation_angle         Optional float. The rotation angle that will be used to generate additional 
                           image chips.

                           An image chip will be generated with a rotation angle of 0, which 
                           means no rotation. It will then be rotated at the specified angle to 
                           create an additional image chip. The same training samples will be 
                           captured at multiple angles in multiple image chips for data augmentation.
                           The default rotation angle is 0.
    ------------------     --------------------------------------------------------------------
    gis                    Optional GIS. The GIS on which this tool runs. If not specified, the active GIS is used.
    ==================     ====================================================================

    :return:
        Output string containing the location of the exported training data

    """

    task = "ExportTrainingDataforDeepLearning"

    gis = _arcgis.env.active_gis if gis is None else gis
    url = gis.properties.helperServices.rasterAnalytics.url
    gptool = _arcgis.gis._GISResource(url, gis)

    params = {}

    if output_location:
        params["outputLocation"] = output_location
    else:
        raise RuntimeError("output_location cannot be None")

    if input_raster:
        params["inputRaster"] = _layer_input(input_raster)
    else:
        raise RuntimeError("input_raster cannot be None")

    if input_class_data:
        params["inputClassData"] = _layer_input(input_class_data)

    if chip_format is not None:
        chipFormatAllowedValues = ['TIFF', 'PNG', 'JPEG','MRF']
        if not chip_format in chipFormatAllowedValues:
            raise RuntimeError('chip_format can only be one of the following: '+ str(chipFormatAllowedValues))
        params["chipFormat"] = chip_format

    if tile_size:
        params["tileSize"] = tile_size

    if stride_size:
        params["strideSize"] = stride_size

    if metadata_format is not None:
        metadataFormatAllowedValues = ['KITTI_rectangles', 'PASCAL_VOC_rectangles', 'Classified_Tiles', 'RCNN_Masks', 'Labeled_Tiles']
        if not metadata_format in metadataFormatAllowedValues:
            raise RuntimeError('metadata_format can only be one of the following: '+ str(metadataFormatAllowedValues))

        params['metadataFormat'] = metadata_format

    if buffer_radius is not None:
        params["bufferRadius"]= buffer_radius

    if classvalue_field is not None:
        params["classValueField"]= classvalue_field

    if input_mask_polygons:
        params["inputMaskPolygons"] = _layer_input(input_mask_polygons)

    if rotation_angle:
        params["rotationAngle"] = rotation_angle

    _set_context(params, context)

    task_url, job_info, job_id = _analysis_job(gptool, task, params)

    job_info = _analysis_job_status(gptool, task_url, job_info)
    job_values = _analysis_job_results(gptool, task_url, job_info, job_id)
    item_properties = {
        "properties": {
            "jobUrl": task_url + '/jobs/' + job_info['jobId'],
            "jobType": "GPServer",
            "jobId": job_info['jobId'],
            "jobStatus": "completed"
        }
    }
    return job_values["outLocation"]["uri"]
Exemplo n.º 6
0
def classify_pixels(input_raster,
                    model,
                    model_arguments=None,
                    output_name=None,
                    context=None,
                    *,
                    gis=None,
                    **kwargs):

    """
    Function to classify input imagery data using a deep learning model.
    Note that the deep learning library needs to be installed separately,
    in addition to the server's built in Python 3.x library.

    ==================     ====================================================================
    **Argument**           **Description**
    ------------------     --------------------------------------------------------------------
    input_raster           Required. raster layer that needs to be classified
    ------------------     --------------------------------------------------------------------
    model                  Required model object.
    ------------------     --------------------------------------------------------------------
    model_arguments        Optional dictionary. Name-value pairs of arguments and their values that can be customized by the clients.
                           eg: {"name1":"value1", "name2": "value2"}

    ------------------     --------------------------------------------------------------------
    output_name            Optional. If not provided, an imagery layer is created by the method and used as the output .
                           You can pass in an existing Image Service Item from your GIS to use that instead.
                           Alternatively, you can pass in the name of the output Image Service that should be created by this method
                           to be used as the output for the tool.
                           A RuntimeError is raised if a service by that name already exists
    ------------------     --------------------------------------------------------------------
    context                Optional dictionary. Context contains additional settings that affect task execution.
                           Dictionary can contain value for following keys:

                           - outSR - (Output Spatial Reference) Saves the result in the specified spatial reference

                           - snapRaster - Function will adjust the extent of output rasters so that they 
                             match the cell alignment of the specified snap raster.

                           - cellSize - Set the output raster cell size, or resolution

                           - extent - Sets the processing extent used by the function

                           - parallelProcessingFactor - Sets the parallel processing factor. Default is "80%"

                           - processorType - Sets the processor type. "CPU" or "GPU"

                           Eg: {"outSR" : {spatial reference}}

                           Setting context parameter will override the values set using arcgis.env 
                           variable for this particular function.
    ------------------     --------------------------------------------------------------------
    gis                    Optional GIS. The GIS on which this tool runs. If not specified, the active GIS is used.
    ==================     ====================================================================

    :return:
        The classified imagery layer item

    """


    task = "ClassifyPixelsUsingDeepLearning"

    gis = _arcgis.env.active_gis if gis is None else gis
    url = gis.properties.helperServices.rasterAnalytics.url
    gptool = _arcgis.gis._GISResource(url, gis)

    output_service = None

    output_raster, output_service = _set_output_raster(output_name, task, gis, kwargs)

    params = {}

    params["outputClassifiedRaster"] = output_raster

    params["inputRaster"] = _layer_input(input_raster)

    if model is None:
        raise RuntimeError('model cannot be None')
    else:
        _set_param(gis, params, "model", model)

    if model_arguments:
        params["modelArguments"] = dict((str(k),str(v)) for k, v in model_arguments.items())

    _set_context(params, context)

    task_url, job_info, job_id = _analysis_job(gptool, task, params)

    job_info = _analysis_job_status(gptool, task_url, job_info)
    job_values = _analysis_job_results(gptool, task_url, job_info, job_id)
    item_properties = {
        "properties": {
            "jobUrl": task_url + '/jobs/' + job_info['jobId'],
            "jobType": "GPServer",
            "jobId": job_info['jobId'],
            "jobStatus": "completed"
        }
    }
    output_service.update(item_properties)
    return output_service
Exemplo n.º 7
0
def detect_objects(input_raster,
                   model,
                   model_arguments=None,
                   output_name=None,
                   run_nms=False,
                   confidence_score_field=None,
                   class_value_field=None,
                   max_overlap_ratio=0,
                   context=None,
                   *,
                   gis=None,
                   **kwargs):

    """
    Function can be used to generate feature service that contains polygons on detected objects
    found in the imagery data using the designated deep learning model. Note that the deep learning
    library needs to be installed separately, in addition to the server's built in Python 3.x library.

    ====================================     ====================================================================
    **Argument**                             **Description**
    ------------------------------------     --------------------------------------------------------------------
    input_raster                             Required. raster layer that contains objects that needs to be detected.
    ------------------------------------     --------------------------------------------------------------------
    model                                    Required model object. 
    ------------------------------------     --------------------------------------------------------------------
    model_arguments                          Optional dictionary. Name-value pairs of arguments and their values that can be customized by the clients.
                                             
                                             eg: {"name1":"value1", "name2": "value2"}
    ------------------------------------     --------------------------------------------------------------------
    output_name                              Optional. If not provided, a Feature layer is created by the method and used as the output .
                                             You can pass in an existing Feature Service Item from your GIS to use that instead.
                                             Alternatively, you can pass in the name of the output Feature Service that should be created by this method
                                             to be used as the output for the tool.
                                             A RuntimeError is raised if a service by that name already exists
    ------------------------------------     --------------------------------------------------------------------
    run_nms                                  Optional bool. Default value is False. If set to True, runs the Non Maximum Suppression tool.
    ------------------------------------     --------------------------------------------------------------------
    confidence_score_field                   Optional string. The field in the feature class that contains the confidence scores as output by the object detection method.
                                             This parameter is required when you set the run_nms to True
    ------------------------------------     --------------------------------------------------------------------
    class_value_field                        Optional string. The class value field in the input feature class. 
                                             If not specified, the function will use the standard class value fields 
                                             Classvalue and Value. If these fields do not exist, all features will 
                                             be treated as the same object class.
                                             Set only if run_nms  is set to True
    ------------------------------------     --------------------------------------------------------------------
    max_overlap_ratio                        Optional integer. The maximum overlap ratio for two overlapping features. 
                                             Defined as the ratio of intersection area over union area. 
                                             Set only if run_nms  is set to True
    ------------------------------------     --------------------------------------------------------------------
    context                                  Optional dictionary. Context contains additional settings that affect task execution.
                                             Dictionary can contain value for following keys:

                                             - cellSize - Set the output raster cell size, or resolution

                                             - extent - Sets the processing extent used by the function

                                             - parallelProcessingFactor - Sets the parallel processing factor. Default is "80%"

                                             - processorType - Sets the processor type. "CPU" or "GPU"

                                             Eg: {"processorType" : "CPU"}

                                             Setting context parameter will override the values set using arcgis.env 
                                             variable for this particular function.
    ------------------------------------     --------------------------------------------------------------------
    gis                                      Optional GIS. The GIS on which this tool runs. If not specified, the active GIS is used.
    ====================================     ====================================================================

    :return:
        The output feature layer item containing the detected objects

    """


    task = "DetectObjectsUsingDeepLearning"

    gis = _arcgis.env.active_gis if gis is None else gis
    url = gis.properties.helperServices.rasterAnalytics.url
    gptool = _arcgis.gis._GISResource(url, gis)

    params = {}

    params["inputRaster"] = _layer_input(input_raster)

    if output_name is None:
        output_service_name = 'DetectObjectsUsingDeepLearning_' + _id_generator()
        output_name = output_service_name.replace(' ', '_')
    else:
        output_service_name = output_name.replace(' ', '_')

    folder = None
    folderId = None
    if kwargs is not None:
        if "folder" in kwargs:
                folder = kwargs["folder"]
        if folder is not None:
            if isinstance(folder, dict):
                if "id" in folder:
                    folderId = folder["id"]
                    folder=folder["title"]
            else:
                owner = gis.properties.user.username
                folderId = gis._portal.get_folder_id(owner, folder)
            if folderId is None:
                folder_dict = gis.content.create_folder(folder, owner)
                folder = folder_dict["title"]
                folderId = folder_dict["id"]

    output_service = _create_output_feature_service(gis, output_name, output_service_name, 'Detect Objects', folder)

    if folderId is not None:
        params["outputObjects"] = _json.dumps({"serviceProperties": {"name": output_service_name, "serviceUrl": output_service.url},
                                               "itemProperties": {"itemId": output_service.itemid}, "folderId":folderId})
    else:
        params["outputObjects"] = _json.dumps({"serviceProperties": {"name": output_service_name, "serviceUrl": output_service.url},
                                               "itemProperties": {"itemId": output_service.itemid}})

    if model is None:
        raise RuntimeError('model cannot be None')
    else:
        _set_param(gis, params, "model", model)

    if model_arguments:
        params["modelArguments"] = dict((str(k),str(v)) for k, v in model_arguments.items())

    if isinstance(run_nms, bool):
        if run_nms:
            params["runNMS"] = True

            if confidence_score_field is not None:
                params["confidenceScoreField"] = confidence_score_field

            if class_value_field is not None:
                params["classValueField"] = class_value_field
    
            if max_overlap_ratio is not None:
                params["maxOverlapRatio"] = max_overlap_ratio
        else:
            params["runNMS"] = False
    else:
        raise RuntimeError("run_nms value should be an instance of bool")
    
    _set_context(params, context)

    task_url, job_info, job_id = _analysis_job(gptool, task, params)

    job_info = _analysis_job_status(gptool, task_url, job_info)
    job_values = _analysis_job_results(gptool, task_url, job_info, job_id)
    item_properties = {
        "properties": {
            "jobUrl": task_url + '/jobs/' + job_info['jobId'],
            "jobType": "GPServer",
            "jobId": job_info['jobId'],
            "jobStatus": "completed"
        }
    }
    output_service.update(item_properties)
    return output_service