o
    e$                    @   s   d dl Z d dlZd dlZd dlZd dlmZ d dlmZm	Z	 ddl
mZ ddlmZ ddlmZ dd	lmZmZ dd
lmZmZmZmZmZ dedjd d  d ZeZG dd dZG dd deZdS )    N)MessageToJson)service_pb2service_pb2_grpc   )InferenceServerClientBase)Request   )InferResult)_InferStream_RequestIterator)_get_inference_request_grpc_compression_typeget_error_grpcraise_errorraise_error_grpci   c                   @   s"   e Zd ZdZedddfddZdS )KeepAliveOptionsa  A KeepAliveOptions object is used to encapsulate GRPC KeepAlive
    related parameters for initiating an InferenceServerclient object.

    See the https://github.com/grpc/grpc/blob/master/doc/keepalive.md
    documentation for more information.

    Parameters
    ----------
    keepalive_time_ms: int
        The period (in milliseconds) after which a keepalive ping is sent on
        the transport. Default is INT32_MAX.

    keepalive_timeout_ms: int
        The period (in milliseconds) the sender of the keepalive ping waits
        for an acknowledgement. If it does not receive an acknowledgment
        within this time, it will close the connection. Default is 20000
        (20 seconds).

    keepalive_permit_without_calls: bool
        Allows keepalive pings to be sent even if there are no calls in flight.
        Default is False.

    http2_max_pings_without_data: int
        The maximum number of pings that can be sent when there is no
        data/header frame to be sent. gRPC Core will not continue sending
        pings if we run over the limit. Setting it to 0 allows sending pings
        without such a restriction. Default is 2.

    i N  Fr   c                 C   s   || _ || _|| _|| _d S N)keepalive_time_mskeepalive_timeout_mskeepalive_permit_without_callshttp2_max_pings_without_data)selfr   r   r   r    r   ID:\Projects\ConvertPro\env\Lib\site-packages\tritonclient/grpc/_client.py__init__W   s   
zKeepAliveOptions.__init__N)__name__
__module____qualname____doc__	INT32_MAXr   r   r   r   r   r   8   s     r   c                       s  e Zd ZdZ								dD fdd	Zdd Zdd	 Zd
d Zdd Zdd Z	dEddZ
dEddZdFddZdGddZ	dHddZ	dHddZdGddZdIdd ZdGd!d"Z	dJd#d$Zdi ddfd%d&ZdKd'd(ZdGd)d*ZdGd+d,Z	dHd-d.Z	dLd0d1ZdFd2d3Z	dHd4d5Z	dEd6d7ZdFd8d9Z				/			/					dMd:d;Z				/			/					dMd<d=Z	dId>d?Z d@dA Z!				/				/		dNdBdCZ"  Z#S )OInferenceServerClienta	  An InferenceServerClient object is used to perform any kind of
    communication with the InferenceServer using gRPC protocol. Most
    of the methods are thread-safe except start_stream, stop_stream
    and async_stream_infer. Accessing a client stream with different
    threads will cause undefined behavior.

    Parameters
    ----------
    url : str
        The inference server URL, e.g. 'localhost:8001'.

    verbose : bool
        If True generate verbose output. Default value is False.

    ssl : bool
        If True use SSL encrypted secure channel. Default is False.

    root_certificates : str
        File holding the PEM-encoded root certificates as a byte
        string, or None to retrieve them from a default location
        chosen by gRPC runtime. The option is ignored if `ssl`
        is False. Default is None.

    private_key : str
        File holding the PEM-encoded private key as a byte string,
        or None if no private key should be used. The option is
        ignored if `ssl` is False. Default is None.

    certificate_chain : str
        File holding PEM-encoded certificate chain as a byte string
        to use or None if no certificate chain should be used. The
        option is ignored if `ssl` is False. Default is None.

    creds: grpc.ChannelCredentials
        A grpc.ChannelCredentials object to use for the connection.
        The ssl, root_certificates, private_key and certificate_chain
        options will be ignored when using this option. Default is None.

    keepalive_options: KeepAliveOptions
        Object encapsulating various GRPC KeepAlive options. See
        the class definition for more information. Default is None.

    channel_args: List[Tuple]
        List of Tuple pairs ("key", value) to be passed directly to the GRPC
        channel as the channel_arguments. If this argument is provided, it is
        expected the channel arguments are correct and complete, and the
        keepalive_options parameter will be ignored since the corresponding
        keepalive channel arguments can be set directly in this parameter. See
        https://grpc.github.io/grpc/python/glossary.html#term-channel_arguments
        for more details. Default is None.

    Raises
    ------
    Exception
        If unable to create a client.
    FNc
                    sz  t    |	d ur|	}
n|st }dtfdtfd|jfd|jfd|jfd|jfg}
|r5tj	|||
d| _
ny|rd  } }}|d urZt|d}| }W d    n1 sUw   Y  |d urwt|d}| }W d    n1 srw   Y  |d urt|d}| }W d    n1 sw   Y  tj|||d	}tj	|||
d| _
ntj||
d| _
t| j
| _|| _d | _d S )
Nzgrpc.max_send_message_lengthzgrpc.max_receive_message_lengthzgrpc.keepalive_time_mszgrpc.keepalive_timeout_msz#grpc.keepalive_permit_without_callsz!grpc.http2.max_pings_without_data)optionsrb)root_certificatesprivate_keycertificate_chain)superr   r   MAX_GRPC_MESSAGE_SIZEr   r   r   r   grpcZsecure_channel_channelopenreadZssl_channel_credentialsZinsecure_channelr   ZGRPCInferenceServiceStub_client_stub_verbose_stream)r   urlverbosesslr%   r&   r'   credsZkeepalive_optionsZchannel_argsZchannel_optZrc_bytesZpk_bytesZcc_bytesZrc_fsZpk_fsZcc_fs	__class__r   r   r      sT   




zInferenceServerClient.__init__c                 C   s2   t |}| | |jd ur|j }|S d}|S )Nr   )r   Z_call_pluginheadersitems)r   r7   requestZrequest_metadatar   r   r   _get_metadata   s   
z#InferenceServerClient._get_metadatac                 C   s   | S r   r   r   r   r   r   	__enter__   s   zInferenceServerClient.__enter__c                 C      |    d S r   close)r   typevalue	tracebackr   r   r   __exit__      zInferenceServerClient.__exit__c                 C   r=   r   r>   r;   r   r   r   __del__   rD   zInferenceServerClient.__del__c                 C   s   |    | j  dS )zWClose the client. Any future calls to server
        will result in an Error.

        N)stop_streamr+   r?   r;   r   r   r   r?      s   zInferenceServerClient.closec              
   C      |  |}z"t }| jrtd|| | jj||d}| jr$t| |jW S  t	j
y? } zt| W Y d}~dS d}~ww )a  Contact the inference server and get liveness.

        Parameters
        ----------
        headers: dict
            Optional dictionary specifying additional HTTP
            headers to include in the request.

        Returns
        -------
        bool
            True if server is live, False if server is not live.

        Raises
        ------
        InferenceServerException
            If unable to get liveness.

        zis_server_live, metadata {}
{}r9   metadataN)r:   r   ZServerLiveRequestr/   printformatr.   Z
ServerLiveliver*   RpcErrorr   r   r7   rI   r9   response	rpc_errorr   r   r   is_server_live      
z$InferenceServerClient.is_server_livec              
   C   rG   )a  Contact the inference server and get readiness.

        Parameters
        ----------
        headers: dict
            Optional dictionary specifying additional HTTP
            headers to include in the request.

        Returns
        -------
        bool
            True if server is ready, False if server is not ready.

        Raises
        ------
        InferenceServerException
            If unable to get readiness.

        zis_server_ready, metadata {}
{}rH   N)r:   r   ZServerReadyRequestr/   rJ   rK   r.   ZServerReadyreadyr*   rM   r   rN   r   r   r   is_server_ready  rR   z%InferenceServerClient.is_server_ready c              
   C   s   |  |}z/t|tkrtd tj||d}| jr"td|| | j	j
||d}| jr1t| |jW S  tjyL } zt| W Y d}~dS d}~ww )a  Contact the inference server and get the readiness of specified model.

        Parameters
        ----------
        model_name: str
            The name of the model to check for readiness.
        model_version: str
            The version of the model to check for readiness. The default value
            is an empty string which means then the server will choose a version
            based on the model and internal policy.
        headers: dict
            Optional dictionary specifying additional HTTP
            headers to include in the request.

        Returns
        -------
        bool
            True if the model is ready, False if not ready.

        Raises
        ------
        InferenceServerException
            If unable to get model readiness.

        model version must be a stringnameversionzis_model_ready, metadata {}
{}rH   N)r:   r@   strr   r   ZModelReadyRequestr/   rJ   rK   r.   Z
ModelReadyrS   r*   rM   r   )r   
model_namemodel_versionr7   rI   r9   rO   rP   r   r   r   is_model_ready8  s"   
z$InferenceServerClient.is_model_readyc              
   C      |  |}z-t }| jrtd|| | jj||d}| jr$t| |r0t	t
|ddW S |W S  tjyJ } zt| W Y d}~dS d}~ww )a  Contact the inference server and get its metadata.

        Parameters
        ----------
        headers: dict
            Optional dictionary specifying additional HTTP
            headers to include in the request.
        as_json : bool
            If True then returns server metadata as a json dict,
            otherwise as a protobuf message. Default value is
            False. The returned json is generated from the protobuf
            message using MessageToJson and as a result int64 values
            are represented as string. It is the caller's
            responsibility to convert these strings back to int64
            values as necessary.

        Returns
        -------
        dict or protobuf message
            The JSON dict or ServerMetadataResponse message
            holding the metadata.

        Raises
        ------
        InferenceServerException
            If unable to get server metadata.

        z#get_server_metadata, metadata {}
{}rH   TZpreserving_proto_field_nameN)r:   r   ZServerMetadataRequestr/   rJ   rK   r.   ZServerMetadatajsonloadsr   r*   rM   r   r   r7   as_jsonrI   r9   rO   rP   r   r   r   get_server_metadatab  s&   

z)InferenceServerClient.get_server_metadatac           	   
   C      |  |}z:t|tkrtd tj||d}| jr"td|| | j	j
||d}| jr1t| |r=tt|ddW S |W S  tjyW } zt| W Y d}~dS d}~ww )a  Contact the inference server and get the metadata for specified model.

        Parameters
        ----------
        model_name: str
            The name of the model
        model_version: str
            The version of the model to get metadata. The default value
            is an empty string which means then the server will choose
            a version based on the model and internal policy.
        headers: dict
            Optional dictionary specifying additional HTTP
            headers to include in the request.
        as_json : bool
            If True then returns model metadata as a json dict,
            otherwise as a protobuf message. Default value is False.
            The returned json is generated from the protobuf message
            using MessageToJson and as a result int64 values are
            represented as string. It is the caller's responsibility
            to convert these strings back to int64 values as
            necessary.

        Returns
        -------
        dict or protobuf message
            The JSON dict or ModelMetadataResponse message holding
            the metadata.

        Raises
        ------
        InferenceServerException
            If unable to get model metadata.

        rV   rW   z"get_model_metadata, metadata {}
{}rH   Tr_   N)r:   r@   rZ   r   r   ZModelMetadataRequestr/   rJ   rK   r.   ZModelMetadatar`   ra   r   r*   rM   r   	r   r[   r\   r7   rc   rI   r9   rO   rP   r   r   r   get_model_metadata  s.   
%
z(InferenceServerClient.get_model_metadatac           	   
   C   re   )a  Contact the inference server and get the configuration for specified model.

        Parameters
        ----------
        model_name: str
            The name of the model
        model_version: str
            The version of the model to get configuration. The default value
            is an empty string which means then the server will choose
            a version based on the model and internal policy.
        headers: dict
            Optional dictionary specifying additional HTTP
            headers to include in the request.
        as_json : bool
            If True then returns configuration as a json dict, otherwise
            as a protobuf message. Default value is False.
            The returned json is generated from the protobuf message
            using MessageToJson and as a result int64 values are
            represented as string. It is the caller's responsibility
            to convert these strings back to int64 values as
            necessary.

        Returns
        -------
        dict or protobuf message
            The JSON dict or ModelConfigResponse message holding
            the metadata.

        Raises
        ------
        InferenceServerException
            If unable to get model configuration.

        rV   rW   z get_model_config, metadata {}
{}rH   Tr_   N)r:   r@   rZ   r   r   ZModelConfigRequestr/   rJ   rK   r.   ZModelConfigr`   ra   r   r*   rM   r   rf   r   r   r   get_model_config  s*   
%
z&InferenceServerClient.get_model_configc              
   C   r^   )aY  Get the index of model repository contents

        Parameters
        ----------
        headers: dict
            Optional dictionary specifying additional HTTP
            headers to include in the request.
        as_json : bool
            If True then returns model repository index
            as a json dict, otherwise as a protobuf message.
            Default value is False.
            The returned json is generated from the protobuf message
            using MessageToJson and as a result int64 values are
            represented as string. It is the caller's responsibility
            to convert these strings back to int64 values as
            necessary.

        Returns
        -------
        dict or protobuf message
            The JSON dict or RepositoryIndexResponse message holding
            the model repository index.

        z*get_model_repository_index, metadata {}
{}rH   Tr_   N)r:   r   ZRepositoryIndexRequestr/   rJ   rK   r.   ZRepositoryIndexr`   ra   r   r*   rM   r   rb   r   r   r   get_model_repository_index  s.   

z0InferenceServerClient.get_model_repository_indexc           
   
   C   s   |  |}zFtj|d}|dur||jd _| jr!td|| |dur4| D ]
\}}||j| _	q)| j
j||d | jrItd| W dS W dS  tjyc }	 zt|	 W Y d}	~	dS d}	~	ww )a  Request the inference server to load or reload specified model.

        Parameters
        ----------
        model_name : str
            The name of the model to be loaded.
        headers: dict
            Optional dictionary specifying additional HTTP
            headers to include in the request.
        config: str
            Optional JSON representation of a model config provided for
            the load request, if provided, this config will be used for
            loading the model.
        files: dict
            Optional dictionary specifying file path (with "file:" prefix) in
            the override model directory to the file content as bytes.
            The files will form the model directory that the model will be
            loaded from. If specified, 'config' must be provided to be
            the model configuration of the override model directory.

        Raises
        ------
        InferenceServerException
            If unable to load the model.

        r[   Nconfigz2load_model, metadata {}
override files omitted:
{}rH   zLoaded model '{}')r:   r   ZRepositoryModelLoadRequest
parametersstring_paramr/   rJ   rK   r8   Zbytes_paramr.   ZRepositoryModelLoadr*   rM   r   )
r   r[   r7   rk   filesrI   r9   pathcontentrP   r   r   r   
load_model8  s,   
z InferenceServerClient.load_modelc              
   C   s   |  |}z/tj|d}||jd _| jrtd|| | jj	||d | jr2td| W dS W dS  t
jyL } zt| W Y d}~dS d}~ww )a  Request the inference server to unload specified model.

        Parameters
        ----------
        model_name : str
            The name of the model to be unloaded.
        headers: dict
            Optional dictionary specifying additional HTTP
            headers to include in the request.
        unload_dependents : bool
            Whether the dependents of the model should also be unloaded.

        Raises
        ------
        InferenceServerException
            If unable to unload the model.

        rj   unload_dependentszunload_model, metadata {}
{}rH   zUnloaded model '{}'N)r:   r   ZRepositoryModelUnloadRequestrl   
bool_paramr/   rJ   rK   r.   ZRepositoryModelUnloadr*   rM   r   )r   r[   r7   rr   rI   r9   rP   r   r   r   unload_modelh  s   
z"InferenceServerClient.unload_modelc           	   
   C   re   )a  Get the inference statistics for the specified model name and
        version.

        Parameters
        ----------
        model_name : str
            The name of the model to get statistics. The default value is
            an empty string, which means statistics of all models will
            be returned.
        model_version: str
            The version of the model to get inference statistics. The
            default value is an empty string which means then the server
            will return the statistics of all available model versions.
        headers: dict
            Optional dictionary specifying additional HTTP
            headers to include in the request.
        as_json : bool
            If True then returns inference statistics
            as a json dict, otherwise as a protobuf message.
            Default value is False.
            The returned json is generated from the protobuf message
            using MessageToJson and as a result int64 values are
            represented as string. It is the caller's responsibility
            to convert these strings back to int64 values as
            necessary.

        Raises
        ------
        InferenceServerException
            If unable to get the model inference statistics.

        rV   rW   z(get_inference_statistics, metadata {}
{}rH   Tr_   N)r:   r@   rZ   r   r   ZModelStatisticsRequestr/   rJ   rK   r.   ZModelStatisticsr`   ra   r   r*   rM   r   rf   r   r   r   get_inference_statistics  s6   
#
z.InferenceServerClient.get_inference_statisticsc              
   C   s   |  |}z\t }|dur|dkr||_| D ]\}}|du r'|j|  q|j| jt|t	r4|n|g q| j
rDtd|| | jj||d}	| j
rSt|	 |r_tt|	ddW S |	W S  tjyy }
 zt|
 W Y d}
~
dS d}
~
ww )a  Update the trace settings for the specified model name, or
        global trace settings if model name is not given.
        Returns the trace settings after the update.

        Parameters
        ----------
        model_name : str
            The name of the model to update trace settings. Specifying None or
            empty string will update the global trace settings.
            The default value is None.
        settings: dict
            The new trace setting values. Only the settings listed will be
            updated. If a trace setting is listed in the dictionary with
            a value of 'None', that setting will be cleared.
        headers: dict
            Optional dictionary specifying additional HTTP
            headers to include in the request.
        as_json : bool
            If True then returns trace settings
            as a json dict, otherwise as a protobuf message.
            Default value is False.
            The returned json is generated from the protobuf message
            using MessageToJson and as a result int64 values are
            represented as string. It is the caller's responsibility
            to convert these strings back to int64 values as
            necessary.

        Returns
        -------
        dict or protobuf message
            The JSON dict or TraceSettingResponse message holding
            the updated trace settings.

        Raises
        ------
        InferenceServerException
            If unable to update the trace settings.

        NrU   z%update_trace_settings, metadata {}
{}rH   Tr_   )r:   r   TraceSettingRequestr[   r8   settingsrA   extend
isinstancelistr/   rJ   rK   r.   TraceSettingr`   ra   r   r*   rM   r   )r   r[   rw   r7   rc   rI   r9   keyrA   rO   rP   r   r   r   update_trace_settings  s:   
*

z+InferenceServerClient.update_trace_settingsc              
   C   s   |  |}z8t }|dur|dkr||_| jr td|| | jj||d}| jr/t| |r;t	
t|ddW S |W S  tjyU } zt| W Y d}~dS d}~ww )a  Get the trace settings for the specified model name, or global trace
        settings if model name is not given

        Parameters
        ----------
        model_name : str
            The name of the model to get trace settings. Specifying None or
            empty string will return the global trace settings.
            The default value is None.
        headers: dict
            Optional dictionary specifying additional HTTP
            headers to include in the request.
        as_json : bool
            If True then returns trace settings
            as a json dict, otherwise as a protobuf message.
            Default value is False.
            The returned json is generated from the protobuf message
            using MessageToJson and as a result int64 values are
            represented as string. It is the caller's responsibility
            to convert these strings back to int64 values as
            necessary.

        Returns
        -------
        dict or protobuf message
            The JSON dict or TraceSettingResponse message holding
            the trace settings.

        Raises
        ------
        InferenceServerException
            If unable to get the trace settings.

        NrU   z"get_trace_settings, metadata {}
{}rH   Tr_   )r:   r   rv   r[   r/   rJ   rK   r.   r{   r`   ra   r   r*   rM   r   )r   r[   r7   rc   rI   r9   rO   rP   r   r   r   get_trace_settings  s*   
#
z(InferenceServerClient.get_trace_settingsc           
   
   C   s   |  |}z`t }| D ].\}}|du r|j|  q|dks$|dkr+||j| _q|dkr6||j| _q||j| _q| jrHt	d
|| | jj||d}| jrWt	| |rctt|ddW S |W S  tjy} }	 zt|	 W Y d}	~	dS d}	~	ww )	aV  Update the global log settings.
        Returns the log settings after the update.
        Parameters
        ----------
        settings: dict
            The new log setting values. Only the settings listed will be
            updated.
        headers: dict
            Optional dictionary specifying additional HTTP
            headers to include in the request.
        as_json : bool
            If True then returns trace settings
            as a json dict, otherwise as a protobuf message.
            Default value is False.
            The returned json is generated from the protobuf message
            using MessageToJson and as a result int64 values are
            represented as string. It is the caller's responsibility
            to convert these strings back to int64 values as
            necessary.
        Returns
        -------
        dict or protobuf message
            The JSON dict or LogSettingsResponse message holding
            the updated log settings.
        Raises
        ------
        InferenceServerException
            If unable to update the log settings.
        NZlog_fileZ
log_formatZlog_verbose_levelz#update_log_settings, metadata {}
{}rH   Tr_   )r:   r   LogSettingsRequestr8   rw   rm   Zuint32_paramrs   r/   rJ   rK   r.   LogSettingsr`   ra   r   r*   rM   r   )
r   rw   r7   rc   rI   r9   r|   rA   rO   rP   r   r   r   update_log_settingsF  s2   

z)InferenceServerClient.update_log_settingsc              
   C   r^   )a  Get the global log settings.
        Parameters
        ----------
        headers: dict
            Optional dictionary specifying additional HTTP
            headers to include in the request.
        as_json : bool
            If True then returns log settings
            as a json dict, otherwise as a protobuf message.
            Default value is False.
            The returned json is generated from the protobuf message
            using MessageToJson and as a result int64 values are
            represented as string. It is the caller's responsibility
            to convert these strings back to int64 values as
            necessary.
        Returns
        -------
        dict or protobuf message
            The JSON dict or LogSettingsResponse message holding
            the log settings.
        Raises
        ------
        InferenceServerException
            If unable to get the log settings.
        z get_log_settings, metadata {}
{}rH   Tr_   N)r:   r   r   r/   rJ   rK   r.   r   r`   ra   r   r*   rM   r   rb   r   r   r   get_log_settings  s"   

z&InferenceServerClient.get_log_settingsc              
   C      |  |}z/tj|d}| jrtd|| | jj||d}| jr&t| |r2t	t
|ddW S |W S  tjyL } zt| W Y d}~dS d}~ww )a  Request system shared memory status from the server.

        Parameters
        ----------
        region_name : str
            The name of the region to query status. The default
            value is an empty string, which means that the status
            of all active system shared memory will be returned.
        headers: dict
            Optional dictionary specifying additional HTTP
            headers to include in the request.
        as_json : bool
            If True then returns system shared memory status as a json
            dict, otherwise as a protobuf message. Default value is
            False.  The returned json is generated from the protobuf
            message using MessageToJson and as a result int64 values
            are represented as string. It is the caller's
            responsibility to convert these strings back to int64
            values as necessary.

        Returns
        -------
        dict or protobuf message
            The JSON dict or SystemSharedMemoryStatusResponse message holding
            the system shared memory status.

        Raises
        ------
        InferenceServerException
            If unable to get the status of specified shared memory.

        rX   z/get_system_shared_memory_status, metadata {}
{}rH   Tr_   N)r:   r   ZSystemSharedMemoryStatusRequestr/   rJ   rK   r.   ZSystemSharedMemoryStatusr`   ra   r   r*   rM   r   r   Zregion_namer7   rc   rI   r9   rO   rP   r   r   r   get_system_shared_memory_status  s.   
#
z5InferenceServerClient.get_system_shared_memory_statusr   c           	   
   C   s   |  |}z,tj||||d}| jrtd|| | jj||d | jr/td| W dS W dS  tj	yI } zt
| W Y d}~dS d}~ww )ap  Request the server to register a system shared memory with the
        following specification.

        Parameters
        ----------
        name : str
            The name of the region to register.
        key : str
            The key of the underlying memory object that contains the
            system shared memory region.
        byte_size : int
            The size of the system shared memory region, in bytes.
        offset : int
            Offset, in bytes, within the underlying memory object to
            the start of the system shared memory region. The default
            value is zero.
        headers: dict
            Optional dictionary specifying additional HTTP
            headers to include in the request.

        Raises
        ------
        InferenceServerException
            If unable to register the specified system shared memory.

        )rX   r|   offset	byte_sizez-register_system_shared_memory, metadata {}
{}rH   z.Registered system shared memory with name '{}'N)r:   r   Z!SystemSharedMemoryRegisterRequestr/   rJ   rK   r.   ZSystemSharedMemoryRegisterr*   rM   r   )	r   rX   r|   r   r   r7   rI   r9   rP   r   r   r   register_system_shared_memory  s*   
z3InferenceServerClient.register_system_shared_memoryc              
   C      |  |}z4tj|d}| jrtd|| | jj||d | jr7|dkr0td| W dS td W dS W dS  tj	yQ } zt
| W Y d}~dS d}~ww )a^  Request the server to unregister a system shared memory with the
        specified name.

        Parameters
        ----------
        name : str
            The name of the region to unregister. The default value is empty
            string which means all the system shared memory regions will be
            unregistered.
        headers: dict
            Optional dictionary specifying additional HTTP
            headers to include in the request.

        Raises
        ------
        InferenceServerException
            If unable to unregister the specified system shared memory region.

        r   z/unregister_system_shared_memory, metadata {}
{}rH   rU   z0Unregistered system shared memory with name '{}'z-Unregistered all system shared memory regionsN)r:   r   Z#SystemSharedMemoryUnregisterRequestr/   rJ   rK   r.   ZSystemSharedMemoryUnregisterr*   rM   r   r   rX   r7   rI   r9   rP   r   r   r   unregister_system_shared_memory  s.   

z5InferenceServerClient.unregister_system_shared_memoryc              
   C   r   )a  Request cuda shared memory status from the server.

        Parameters
        ----------
        region_name : str
            The name of the region to query status. The default
            value is an empty string, which means that the status
            of all active cuda shared memory will be returned.
        headers: dict
            Optional dictionary specifying additional HTTP
            headers to include in the request.
        as_json : bool
            If True then returns cuda shared memory status as a json
            dict, otherwise as a protobuf message. Default value is
            False.  The returned json is generated from the protobuf
            message using MessageToJson and as a result int64 values
            are represented as string. It is the caller's
            responsibility to convert these strings back to int64
            values as necessary.

        Returns
        -------
        dict or protobuf message
            The JSON dict or CudaSharedMemoryStatusResponse message holding
            the cuda shared memory status.

        Raises
        ------
        InferenceServerException
            If unable to get the status of specified shared memory.

        r   z-get_cuda_shared_memory_status, metadata {}
{}rH   Tr_   N)r:   r   ZCudaSharedMemoryStatusRequestr/   rJ   rK   r.   ZCudaSharedMemoryStatusr`   ra   r   r*   rM   r   r   r   r   r   get_cuda_shared_memory_status?  s.   
$
z3InferenceServerClient.get_cuda_shared_memory_statusc           	   
   C   s   |  |}z/tj|t|||d}| jrtd|| | jj	||d | jr2td| W dS W dS  t
jyL } zt| W Y d}~dS d}~ww )a  Request the server to register a system shared memory with the
        following specification.

        Parameters
        ----------
        name : str
            The name of the region to register.
        raw_handle : bytes
            The raw serialized cudaIPC handle in base64 encoding.
        device_id : int
            The GPU device ID on which the cudaIPC handle was created.
        byte_size : int
            The size of the cuda shared memory region, in bytes.
        headers: dict
            Optional dictionary specifying additional HTTP
            headers to include in the request.

        Raises
        ------
        InferenceServerException
            If unable to register the specified cuda shared memory.

        )rX   
raw_handle	device_idr   z+register_cuda_shared_memory, metadata {}
{}rH   z,Registered cuda shared memory with name '{}'N)r:   r   ZCudaSharedMemoryRegisterRequestbase64	b64decoder/   rJ   rK   r.   ZCudaSharedMemoryRegisterr*   rM   r   )	r   rX   r   r   r   r7   rI   r9   rP   r   r   r   register_cuda_shared_memoryz  s0   
z1InferenceServerClient.register_cuda_shared_memoryc              
   C   r   )aX  Request the server to unregister a cuda shared memory with the
        specified name.

        Parameters
        ----------
        name : str
            The name of the region to unregister. The default value is empty
            string which means all the cuda shared memory regions will be
            unregistered.
        headers: dict
            Optional dictionary specifying additional HTTP
            headers to include in the request.

        Raises
        ------
        InferenceServerException
            If unable to unregister the specified cuda shared memory region.

        r   z-unregister_cuda_shared_memory, metadata {}
{}rH   rU   z.Unregistered cuda shared memory with name '{}'z+Unregistered all cuda shared memory regionsN)r:   r   Z!CudaSharedMemoryUnregisterRequestr/   rJ   rK   r.   ZCudaSharedMemoryUnregisterr*   rM   r   r   r   r   r   unregister_cuda_shared_memory  s*   
z3InferenceServerClient.unregister_cuda_shared_memoryc                 C   s   |  |}t|tkrtd t|||||||||	|
|d}| jr)td|| z| jj	|||t
|d}| jr=t| t|}|W S  tjy[ } zt| W Y d}~dS d}~ww )aK  Run synchronous inference using the supplied 'inputs' requesting
        the outputs specified by 'outputs'.

        Parameters
        ----------
        model_name: str
            The name of the model to run inference.
        inputs : list
            A list of InferInput objects, each describing data for a input
            tensor required by the model.
        model_version : str
            The version of the model to run inference. The default value
            is an empty string which means then the server will choose
            a version based on the model and internal policy.
        outputs : list
            A list of InferRequestedOutput objects, each describing how the output
            data must be returned. If not specified all outputs produced
            by the model will be returned using default settings.
        request_id : str
            Optional identifier for the request. If specified will be returned
            in the response. Default value is an empty string which means no
            request_id will be used.
        sequence_id : int
            The unique identifier for the sequence being represented by the
            object. Default value is 0 which means that the request does not
            belong to a sequence.
        sequence_start : bool
            Indicates whether the request being added marks the start of the
            sequence. Default value is False. This argument is ignored if
            'sequence_id' is 0.
        sequence_end : bool
            Indicates whether the request being added marks the end of the
            sequence. Default value is False. This argument is ignored if
            'sequence_id' is 0.
        priority : int
            Indicates the priority of the request. Priority value zero
            indicates that the default priority level should be used
            (i.e. same behavior as not specifying the priority parameter).
            Lower value priorities indicate higher priority levels. Thus
            the highest priority level is indicated by setting the parameter
            to 1, the next highest is 2, etc. If not provided, the server
            will handle the request using default setting for the model.
        timeout : int
            The timeout value for the request, in microseconds. If the request
            cannot be completed within the time the server can take a
            model-specific action such as terminating the request. If not
            provided, the server will handle the request using default setting
            for the model. This option is only respected by the model that is
            configured with dynamic batching. See here for more details:
            https://github.com/triton-inference-server/server/blob/main/docs/user_guide/model_configuration.md#dynamic-batcher
        client_timeout : float
            The maximum end-to-end time, in seconds, the request is allowed
            to take. The client will abort request and raise
            InferenceServerExeption with message "Deadline Exceeded" when the
            specified time elapses. The default value is None which means
            client will wait for the response from the server.
        headers : dict
            Optional dictionary specifying additional HTTP headers to include
            in the request.
        compression_algorithm : str
            Optional grpc compression algorithm to be used on client side.
            Currently supports "deflate", "gzip" and None. By default, no
            compression is used.
        parameters : dict
            Optional custom parameters to be included in the inference
            request.

        Returns
        -------
        InferResult
            The object holding the result of the inference.

        Raises
        ------
        InferenceServerException
            If server fails to perform inference.
        rV   r[   inputsr\   
request_idoutputssequence_idsequence_startsequence_endprioritytimeoutrl   zinfer, metadata {}
{}r9   rI   r   compressionN)r:   r@   rZ   r   r   r/   rJ   rK   r.   
ModelInferr   r	   r*   rM   r   )r   r[   r   r\   r   r   r   r   r   r   r   client_timeoutr7   compression_algorithmrl   rI   r9   rO   resultrP   r   r   r   infer  sB   
^zInferenceServerClient.inferc                    s    fdd} |}t|tkrtd t||||||||	|
||d}jr0td|| z.jj	j
|||t|d_j| jr\d}|dkrU|d	| }t| W d
S W d
S  tjyv } zt| W Y d
}~d
S d
}~ww )a  Run asynchronous inference using the supplied 'inputs' requesting
        the outputs specified by 'outputs'.

        Parameters
        ----------
        model_name: str
            The name of the model to run inference.
        inputs : list
            A list of InferInput objects, each describing data for a input
            tensor required by the model.
        callback : function
            Python function that is invoked once the request is completed.
            The function must reserve the last two arguments (result, error)
            to hold InferResult and InferenceServerException objects
            respectively which will be provided to the function when executing
            the callback. The ownership of these objects will be given to the
            user. The 'error' would be None for a successful inference.
        model_version: str
            The version of the model to run inference. The default value
            is an empty string which means then the server will choose
            a version based on the model and internal policy.
        outputs : list
            A list of InferRequestedOutput objects, each describing how the output
            data must be returned. If not specified all outputs produced
            by the model will be returned using default settings.
        request_id : str
            Optional identifier for the request. If specified will be returned
            in the response. Default value is an empty string which means no
            request_id will be used.
        sequence_id : int
            The unique identifier for the sequence being represented by the
            object. Default value is 0 which means that the request does not
            belong to a sequence.
        sequence_start: bool
            Indicates whether the request being added marks the start of the
            sequence. Default value is False. This argument is ignored if
            'sequence_id' is 0.
        sequence_end: bool
            Indicates whether the request being added marks the end of the
            sequence. Default value is False. This argument is ignored if
            'sequence_id' is 0.
        priority : int
            Indicates the priority of the request. Priority value zero
            indicates that the default priority level should be used
            (i.e. same behavior as not specifying the priority parameter).
            Lower value priorities indicate higher priority levels. Thus
            the highest priority level is indicated by setting the parameter
            to 1, the next highest is 2, etc. If not provided, the server
            will handle the request using default setting for the model.
        timeout : int
            The timeout value for the request, in microseconds. If the request
            cannot be completed within the time the server can take a
            model-specific action such as terminating the request. If not
            provided, the server will handle the request using default setting
            for the model. This option is only respected by the model that is
            configured with dynamic batching. See here for more details:
            https://github.com/triton-inference-server/server/blob/main/docs/user_guide/model_configuration.md#dynamic-batcher
            The maximum end-to-end time, in seconds, the request is allowed
            to take. The client will abort request and provide
            error with message "Deadline Exceeded" in the callback when the
            specified time elapses. The default value is None which means
            client will wait for the response from the server.
        headers: dict
            Optional dictionary specifying additional HTTP
            headers to include in the request.
        compression_algorithm : str
            Optional grpc compression algorithm to be used on client side.
            Currently supports "deflate", "gzip" and None. By default, no
            compression is used.
        parameters : dict
            Optional custom parameters to be included in the inference
            request.

        Raises
        ------
        InferenceServerException
            If server fails to issue inference.
        c              
      sj   d  }}z|   }jrt| t|}W n tjy, } z
t|}W Y d }~nd }~ww  ||d d S )N)r   error)r   r/   rJ   r	   r*   rM   r   )Zcall_futurer   r   rO   rP   callbackr   r   r   wrapped_callback  s   z;InferenceServerClient.async_infer.<locals>.wrapped_callbackrV   r   zasync_infer, metadata {}
{}r   zSent requestrU   z '{}'N)r:   r@   rZ   r   r   r/   rJ   rK   r.   r   futurer   Z_call_futureadd_done_callbackr*   rM   r   )r   r[   r   r   r\   r   r   r   r   r   r   r   r   r7   r   rl   r   rI   r9   Zverbose_messagerP   r   r   r   async_inferS  sJ   a
z!InferenceServerClient.async_inferc              
   C   s   | j dur	td | |}t|| j| _ z| jjt| j ||t|d}| j 	| W dS  t
jyE } zt| W Y d}~dS d}~ww )a|  Starts a grpc bi-directional stream to send streaming inferences.
        Note: When using stream, user must ensure the InferenceServerClient.close()
        gets called at exit.

        Parameters
        ----------
        callback : function
            Python function that is invoked upon receiving response from
            the underlying stream. The function must reserve the last two
            arguments (result, error) to hold InferResult and
            InferenceServerException objects respectively which will be
            provided to the function when executing the callback. The
            ownership of these objects will be given to the user. The
            'error' would be None for a successful inference.
        stream_timeout : float
            Optional stream timeout (in seconds). The stream will be closed
            once the specified timeout expires.
        headers: dict
            Optional dictionary specifying additional HTTP
            headers to include in the request.
        compression_algorithm : str
            Optional grpc compression algorithm to be used on client side.
            Currently supports "deflate", "gzip" and None. By default, no
            compression is used.

        Raises
        ------
        InferenceServerException
            If unable to start a stream or a stream was already running
            for this client.

        Nzcannot start another stream with one already running. 'InferenceServerClient' supports only a single active stream at a given time.)rI   r   r   )r0   r   r:   r
   r/   r.   ZModelStreamInferr   r   Z_init_handlerr*   rM   r   )r   r   Zstream_timeoutr7   r   rI   Zresponse_iteratorrP   r   r   r   start_stream  s$   
#
z"InferenceServerClient.start_streamc                 C   s   | j dur
| j   d| _ dS )z Stops a stream if one available.N)r0   r?   r;   r   r   r   rF     s   


z!InferenceServerClient.stop_streamc                 C   s   | j du r	td t|tkrtd t|||||||||
||d}|	r*d|jd _| jr4td	| | j 
| | jrFtd	| dS dS )	aY  Runs an asynchronous inference over gRPC bi-directional streaming
        API. A stream must be established with a call to start_stream()
        before calling this function. All the results will be provided to the
        callback function associated with the stream.

        Parameters
        ----------
        model_name: str
            The name of the model to run inference.
        inputs : list
            A list of InferInput objects, each describing data for a input
            tensor required by the model.
        model_version: str
            The version of the model to run inference. The default value
            is an empty string which means then the server will choose
            a version based on the model and internal policy.
        outputs : list
            A list of InferRequestedOutput objects, each describing how the output
            data must be returned. If not specified all outputs produced
            by the model will be returned using default settings.
        request_id : str
            Optional identifier for the request. If specified will be returned
            in the response. Default value is an empty string which means no
            request_id will be used.
        sequence_id : int or str
            The unique identifier for the sequence being represented by the
            object.  A value of 0 or "" means that the request does not
            belong to a sequence. Default is 0.
        sequence_start: bool
            Indicates whether the request being added marks the start of the
            sequence. Default value is False. This argument is ignored if
            'sequence_id' is 0 or "".
        sequence_end: bool
            Indicates whether the request being added marks the end of the
            sequence. Default value is False. This argument is ignored if
            'sequence_id' is 0 or "".
        enable_empty_final_response: bool
            Indicates whether "empty" responses should be generated and sent
            back to the client from the server during streaming inference when
            they contain the TRITONSERVER_RESPONSE_COMPLETE_FINAL flag.
            This strictly relates to the case of models/backends that send
            flags-only responses (use TRITONBACKEND_ResponseFactorySendFlags(TRITONSERVER_RESPONSE_COMPLETE_FINAL)
            or InferenceResponseSender.send(flags=TRITONSERVER_RESPONSE_COMPLETE_FINAL))
            Currently, this only occurs for decoupled models, and can be
            used to communicate to the client when a request has received
            its final response from the model. If the backend sends the final
            flag along with a non-empty response, this arg is not needed.
            Default value is False.
        priority : int
            Indicates the priority of the request. Priority value zero
            indicates that the default priority level should be used
            (i.e. same behavior as not specifying the priority parameter).
            Lower value priorities indicate higher priority levels. Thus
            the highest priority level is indicated by setting the parameter
            to 1, the next highest is 2, etc. If not provided, the server
            will handle the request using default setting for the model.
        timeout : int
            The timeout value for the request, in microseconds. If the request
            cannot be completed within the time the server can take a
            model-specific action such as terminating the request. If not
            provided, the server will handle the request using default setting
            for the model. This does not stop the grpc stream itself and is only
            respected by the model that is configured with dynamic batching.
            See here for more details:
            https://github.com/triton-inference-server/server/blob/main/docs/user_guide/model_configuration.md#dynamic-batcher
        parameters : dict
            Optional custom parameters to be included in the inference
            request.
        Raises
        ------
        InferenceServerException
            If server fails to issue inference.
        Nz?stream not available, use start_stream() to make one available.rV   r   TZ"triton_enable_empty_final_responsezasync_stream_infer
{}z enqueued request {} to stream...)r0   r   r@   rZ   r   rl   rs   r/   rJ   rK   Z_enqueue_request)r   r[   r   r\   r   r   r   r   r   Zenable_empty_final_responser   r   rl   r9   r   r   r   async_stream_infer"  s6   
Yz(InferenceServerClient.async_stream_infer)FFNNNNNNr   )rU   N)NF)rU   NF)NNN)rU   rU   NF)NNF)r   N)rU   NrU   r   FFr   NNNNN)
rU   NrU   r   FFFr   NN)$r   r   r   r    r   r:   r<   rC   rE   r?   rQ   rT   r]   rd   rg   rh   ri   rq   rt   ru   r}   r~   r   r   r   r   r   r   r   r   r   r   r   rF   r   __classcell__r   r   r5   r   r"   d   s    <@	

 
 
*1
=

:
0
0 
?

I
8
:,
;

0+
<

0,
 
 
8
r"   )r   structr*   Z	rapidjsonr`   Zgoogle.protobuf.json_formatr   Ztritonclient.grpcr   r   Z_clientr   _requestr   Z_infer_resultr	   Z_infer_streamr
   r   _utilsr   r   r   r   r   Structsizer!   r)   r   r"   r   r   r   r   <module>   s   ,