
    &`i%                        U d dl Z d dlmZmZmZmZmZ d dlZd dl	Z
d dlmZ d dlmZmZmZ d dlmZ d dlmZ d dlmZmZ 	 d dlZej        Zn# e$ r dZY nw xY wej        ej        eej        e
j        ej         iZ!eee         ef         e"d<    ed	
           G d de#                      Z$ ed	
           G d de j%                              Z&dS )    N)CallableDictOptionalTypeUnion)DataBatchType)BatchFormat_convert_batch_type_to_numpy_convert_batch_type_to_pandas)Preprocessor)
Checkpoint)DeveloperAPI	PublicAPITYPE_TO_ENUMbeta)	stabilityc                       e Zd ZdZdS )!PredictorNotSerializableExceptionz;Error raised when trying to serialize a Predictor instance.N)__name__
__module____qualname____doc__     g/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/train/predictor.pyr   r       s        EEDr   r   c            	          e Zd ZdZddee         fdZeej	        de
dd fd                        Zedeej        gej        f         dd fd	            Zdee         fd
Zdee         ddfdZeedefd                        Zedefd            Zd ZdedefdZedd            Zedeej        eeej        f         f         deej        eeej        f         f         fd            Zd Z dS )	PredictoraV  Predictors load models from checkpoints to perform inference.

    .. note::
        The base ``Predictor`` class cannot be instantiated directly. Only one of
        its subclasses can be used.

    **How does a Predictor work?**

    Predictors expose a ``predict`` method that accepts an input batch of type
    ``DataBatchType`` and outputs predictions of the same type as the input batch.

    When the ``predict`` method is called the following occurs:

    - The input batch is converted into a pandas DataFrame. Tensor input (like a
      ``np.ndarray``) will be converted into a single column Pandas Dataframe.
    - If there is a :ref:`Preprocessor <preprocessor-ref>` saved in the provided
      :class:`Checkpoint <ray.train.Checkpoint>`, the preprocessor will be used to
      transform the DataFrame.
    - The transformed DataFrame will be passed to the model for inference (via the
      ``predictor._predict_pandas`` method).
    - The predictions will be outputted by ``predict`` in the same type as the
      original input.

    **How do I create a new Predictor?**

    To implement a new Predictor for your particular framework, you should subclass
    the base ``Predictor`` and implement the following two methods:

    1. ``_predict_pandas``: Given a pandas.DataFrame input, return a
       pandas.DataFrame containing predictions.
    2. ``from_checkpoint``: Logic for creating a Predictor from a
       :class:`Checkpoint <ray.train.Checkpoint>`.
    3. Optionally ``_predict_numpy`` for better performance when working with
       tensor data to avoid extra copies from Pandas conversions.
    Npreprocessorc                 "    || _         d| _        dS )zBSubclasseses must call Predictor.__init__() to set a preprocessor.FN)_preprocessor_cast_tensor_columnsselfr   s     r   __init__zPredictor.__init__M   s    5A %*!!!r   
checkpointreturnc                     t           )a  Create a specific predictor from a checkpoint.

        Args:
            checkpoint: Checkpoint to load predictor data from.
            kwargs: Arguments specific to predictor implementations.

        Returns:
            Predictor: Predictor object.
        NotImplementedError)clsr%   kwargss      r   from_checkpointzPredictor.from_checkpointT   
     "!r   
pandas_udfc                 F     G fddt                                  S )zCreate a Predictor from a Pandas UDF.

        Args:
            pandas_udf: A function that takes a pandas.DataFrame and other
                optional kwargs and returns a pandas.DataFrame.
        c                   @    e Zd Zededdf fd            ZdfdZdS )	5Predictor.from_pandas_udf.<locals>.PandasUDFPredictorr%   r&   r   c                                  S Nr   )r*   r%   r+   PandasUDFPredictors      r   r,   zEPredictor.from_pandas_udf.<locals>.PandasUDFPredictor.from_checkpointn   s    ))+++r   pd.DataFramec                      |fi |S r3   r   )r#   dfr+   r.   s      r   _predict_pandaszEPredictor.from_pandas_udf.<locals>.PandasUDFPredictor._predict_pandasr   s    !z"/////r   N)r&   r5   )r   r   r   classmethodr   r,   r8   )r4   r.   s   r   r4   r1   m   si        , ,+ , , , , , [,0 0 0 0 0 0 0 0r   r4   )r   )r*   r.   r4   s    `@r   from_pandas_udfzPredictor.from_pandas_udfb   sN    	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 "!###r   c                     | j         S )z;Get the preprocessor to use prior to executing predictions.r    r#   s    r   get_preprocessorzPredictor.get_preprocessorw   s    !!r   c                     || _         dS )z;Set the preprocessor to use prior to executing predictions.Nr<   r"   s     r   set_preprocessorzPredictor.set_preprocessor{   s    )r   c                     t           j        S )a  Batch format hint for upstream producers to try yielding best block format.

        The preferred batch format to use if both `_predict_pandas` and
        `_predict_numpy` are implemented. Defaults to Pandas.

        Can be overriden by predictor classes depending on the framework type,
        e.g. TorchPredictor prefers Numpy and XGBoostPredictor prefers Pandas as
        native batch format.

        )r	   PANDAS)r*   s    r   preferred_batch_formatz Predictor.preferred_batch_format   s     !!r   c                     | j         t          j         k    }| j        t          j        k    }|r|r|                                 S |rt          j        S |rt          j        S t          d| j         d          )z4Determine the batch format to use for the predictor.z
Predictor zG must implement at least one of `_predict_pandas` and `_predict_numpy`.)	r8   r   _predict_numpyrC   r	   rB   NUMPYr)   r   )r*   has_pandas_implementedhas_numpy_implementeds      r   _batch_format_to_usezPredictor._batch_format_to_use   s     "%!4	8Q!Q # 2i6N N! 
	&; 
	--///# 	%%" 	$$%:S\ : : :  r   c                     d| _         dS )a  Enable automatic tensor column casting.

        If this is called on a predictor, the predictor will cast tensor columns to
        NumPy ndarrays in the input to the preprocessors and cast tensor columns back to
        the tensor extension type in the prediction outputs.
        TN)r!   r=   s    r   _set_cast_tensor_columnsz"Predictor._set_cast_tensor_columns   s     %)!!!r   datac           
      b   t          | d          st          d          	 t          t          |                   }nT# t          $ rG t          dt          |           dt          t                                                               w xY w| j        r| j        	                    |          }| 
                                }|t          j        k    re|t          j        k    r | j        t          |          fi |S |t          j        k    r(t           | j        t#          |          fi |          S dS |t          j        k    rc|t          j        k    r(t#           | j        t          |          fi |          S |t          j        k    r | j        t#          |          fi |S dS dS )a  Perform inference on a batch of data.

        Args:
            data: A batch of input data of type ``DataBatchType``.
            kwargs: Arguments specific to predictor implementations. These are passed
                directly to ``_predict_numpy`` or ``_predict_pandas``.

        Returns:
            DataBatchType:
                Prediction result. The return type will be the same as the input type.
        r    zCSubclasses of Predictor must call Predictor.__init__(preprocessor).zInvalid input data type of z, supported types: N)hasattrr)   r   typeKeyErrorRuntimeErrorlistkeysr    transform_batchrI   r	   rB   r8   r   rF   rE   r
   )r#   rL   r+   batch_formatbatch_format_to_uses        r   predictzPredictor.predict   s    t_-- 	%U  	'T

3LL 	 	 	6d4jj 6 6|0022336 6  	  	<%55d;;D"7799 ;---"k&888+t+1$77 ;A   %(9994'D'(DT(J(JUUfUU   :9 [..."k&8883(D()Ft)L)LWWPVWW   %(999*t*+G+M+MXXQWXXX /.
 :9s
   < ABr5   c                     t           )a  Perform inference on a Pandas DataFrame.

        Args:
            data: A pandas DataFrame to perform predictions on.
            kwargs: Arguments specific to the predictor implementation.

        Returns:
            A pandas DataFrame containing the prediction result.

        r(   r#   rL   r+   s      r   r8   zPredictor._predict_pandas   r-   r   c                     t           )a  Perform inference on a Numpy data.

        All Predictors working with tensor data (like deep learning predictors)
        should implement this method.

        Args:
            data: A Numpy ndarray or dictionary of ndarrays to perform predictions on.
            kwargs: Arguments specific to the predictor implementation.

        Returns:
            A Numpy ndarray or dictionary of ndarray containing the prediction result.

        r(   rY   s      r   rE   zPredictor._predict_numpy   s
    " "!r   c                      t          d          )NzPredictor instances are not serializable. Instead, you may want to serialize a checkpoint and initialize the Predictor with Predictor.from_checkpoint.)r   r=   s    r   
__reduce__zPredictor.__reduce__   s    /)
 
 	
r   r3   )rL   r5   r&   r5   )!r   r   r   r   r   r   r$   r9   abcabstractmethodr   r,   r   pd	DataFramer:   r>   r@   r   r	   rC   rI   rK   r   rW   r8   r   npndarrayr   strrE   r\   r   r   r   r   r   '   s$       " "H* *Xl%; * * * * 
" 
"+ 
" 
" 
"  [
" $!2<.",">?$	$ $ $ [$("(<"8 " " " "*Xl-C * * * * * "{ " " " \ [" [    [ ) ) ).YM .Y .Y .Y .Y .Y` " " " \" ""*d3
?&;;<"	rz4RZ00	1" " " \"$
 
 
 
 
r   r   )'r]   typingr   r   r   r   r   numpyra   pandasr_   ray.air.data_batch_typer   "ray.air.util.data_batch_conversionr	   r
   r   ray.datar   	ray.trainr   ray.util.annotationsr   r   pyarrowTablepa_tableImportErrorrb   rF   dictr`   rB   r   __annotations__rQ   r   ABCr   r   r   r   <module>rs      s   




 8 8 8 8 8 8 8 8 8 8 8 8 8 8         1 1 1 1 1 1         
 " ! ! ! ! !             8 8 8 8 8 8 8 8NNN}HH   HHH
 J!+
L+$8d4&34    V	 	 	 	 	 	 	 	 VV
 V
 V
 V
 V
 V
 V
 V
 V
 V
s   A AA