
    d                        d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	m
Z
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mZmZ ddlmZ dd	lmZ dd
lmZ ddl m!Z! ddl"m#Z# ddl$m%Z% ddl&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z, eed         ddf         Z- e*            r
d dl.Z/ddl0m1Z1  e+            rd dl2Z2d dl3m4Z4m5Z5 ddl6m7Z7 ddl8m9Z9 ndZ5dZ9erddl:m;Z; ddl<m=Z=  e,j>        e?          Z@d ZAd ZBd ZC	 	 	 d>de#deeeDeeE         f                  deeD         deeD         fd ZF	 	 	 d>deeeDeeE         f                  deeD         deeD         fd!ZGd?d"eeD         fd#ZHd$edeeD         d%ee         d&eeDeeDeDf         f         fd'ZI G d( d)eJ          ZK G d* d+e
          ZL G d, d-          ZM G d. d/eM          ZN G d0 d1eM          ZO G d2 d3eM          ZP G d4 d5e
          ZQd6ZR e+            rd d7lSmTZTmUZUmVZVmWZW  e(eR           G d8 d9eQ                      ZX G d: d;eX          ZY G d< d=          ZZdS )@    N)ABCabstractmethod)UserDict)contextmanager)abspathexists)TYPE_CHECKINGAnyDictListOptionalTupleUnion   )custom_object_save)PreTrainedFeatureExtractor)BaseImageProcessor)	ModelCard)
AutoConfig)PreTrainedTokenizer)ModelOutputadd_end_docstringsinfer_frameworkis_tf_availableis_torch_availableloggingGenericTensorztorch.Tensorz	tf.Tensor)TFAutoModel)
DataLoaderDataset)	AutoModel   )
KeyDataset)TFPreTrainedModel)PreTrainedModelc                 V    t          |           dk    rt          d          | d         S )Nr"   z5This collate_fn is meant to be used with batch_size=1r   )len
ValueError)itemss    ;lib/python3.11/site-packages/transformers/pipelines/base.pyno_collate_fnr+   B   s)    
5zzQPQQQ8O    c           	          t          |           }t          | d                  t          j                  r:| d                  j        }t          |          }dv r"t          j        fd| D             d          S |dk    r(dk    r"t          j        fd| D             d          S t          fd| D                       }t          fd	| D                       }| d                  j        }	|d
k    rD||k    r"t          j        fd| D             d          S t          j	        ||f|	          |z   }
nX|dk    r#t          j	        |||d         f|	          |z   }
n/|dk    r)t          j	        |||d         |d         f|	          |z   }
t          |           D ]\  }}|d
k    r|dk    rB|         d                                         |
|t          |         d                    d f<   T|         d                                         |
|d t          |         d                   f<   |dk    r|dk    rE|         d                                         |
|t          |         d                    d d d f<   |         d                                         |
|d t          |         d                   d d f<   +|dk    r|dk    rI|         d                                         |
|t          |         d                    d d d d d f<   |         d                                         |
|d t          |         d                   d d d d f<   |
S fd| D             S )Nr   )pixel_valuesimagec                      g | ]
}|         S  r1   .0itemkeys     r*   
<listcomp>z_pad.<locals>.<listcomp>Q       :::Dd3i:::r,   )dim   input_featuresc                      g | ]
}|         S r1   r1   r2   s     r*   r6   z_pad.<locals>.<listcomp>T   r7   r,   c              3   >   K   | ]}|         j         d          V  dS r"   Nshaper2   s     r*   	<genexpr>z_pad.<locals>.<genexpr>U   .      >>c+>>>>>>r,   c              3   >   K   | ]}|         j         d          V  dS r=   r>   r2   s     r*   r@   z_pad.<locals>.<genexpr>V   rA   r,   r   c                      g | ]
}|         S r1   r1   r2   s     r*   r6   z_pad.<locals>.<listcomp>]   s    !>!>!>$s)!>!>!>r,   )dtype   leftc                      g | ]
}|         S r1   r1   r2   s     r*   r6   z_pad.<locals>.<listcomp>w   s    ,,,dS	,,,r,   )r'   
isinstancetorchTensorr?   catmaxminrD   zeros	enumerateclone)r)   r5   padding_valuepadding_side
batch_sizer?   r8   
max_length
min_lengthrD   tensorir4   s    `           r*   _padrZ   H   s   UJ%(3-.. --a#%jj+++ 9::::E:::BBBBAXX#!1119::::E:::BBBB>>>>>>>>>
>>>>>>>>>
a#!88Z'' y!>!>!>!>!>!>!>AFFFF[*j!9GGG-WFFAXX[*j%)!DERRRUbbFFAXX[*j%)U2Y!OW\]]]`mmF '' 	P 	PGAtaxx6))6:3il6H6H6J6JF1s49Q<0002223359#Yq\5G5G5I5IF11DIaL 1 111226))9=c19K9K9M9MF1s49Q<00022AAA5668<S	!8J8J8L8LF11DIaL 1 111114556))<@IaL<N<N<P<PF1s49Q<00022AAAqqq899;?9Q<;M;M;O;OF11DIaL 1 11111aaa78,,,,e,,,,r,   c                 6    d }d } t          d           $ j        t          d           j         j        }"t          dd           t          dd           }||||k    rt          d| d|           d|||| fd}|S )	NzBPipeline without tokenizer or feature_extractor cannot do batchingzPipeline with tokenizer without pad_token cannot do batching. You can try to set it with `pipe.tokenizer.pad_token_id = model.config.eos_token_id`.rS   rT   zAThe feature extractor, and tokenizer don't agree on padding side  != rightc                    t          | d                                                   }| D ]\}t          |                                          |k    r5t          dt          |                                           d| d          ]i }|D ]<}|dv r

}n	}n|dv r}n|dv rd}n	|d	v rd}nd}t          | ||          ||<   =|S )
Nr   zEThe elements of the batch contain different keys. Cannot batch them (r\   )>   	input_ids>   input_valuesr.   r:   >   p_maskspecial_tokens_maskr"   >   attention_masktoken_type_ids)setkeysr(   rZ   )r)   rg   r4   paddedr5   _padding_valuef_padding_valuefeature_extractorrT   t_padding_value	tokenizers         r*   innerzpad_collate_fn.<locals>.inner   s1   58==??## 	 	D499;;4''  \_`d`i`i`k`k\l\l            (  	I 	ICm##$):)F%4NN%4NNJJJ!0999!"<<<!" "#uc><HHF3KKr,   )r(   pad_token_idrT   getattr)rm   rk   t_padding_sidef_padding_sidern   rj   rT   rl   s   ``   @@@r*   pad_collate_fnrs   z   s   NN.6]^^^!)M  
 (4O&3N$!"3_dKK !2NDII!n&@^WeEeEetP^ttdrtt
 
 	
 L!%!%        : Lr,   configmodel_classestask	frameworkc                    t                      st                      st          d          t          | t                    r(||d<   d}t                      o|dv }t                      o|dv }|rB|r||                    dt          f          z   }|r||                    dt          f          z   }|j        rg }	|j        D ]m}
t          j
        d          }|r(t          ||
d	          }||	                    |           |r+t          |d
|
 d	          }||	                    |           n|t          |	          z   }t          |          dk    rt          d|            |D ]}|                                }|dk    r5|                     d          r d|d<   t$                              d           n:|dk    r4|                     d          rd|d<   t$                              d           	  |j        | fi |} t+          | d          r|                                 }  n# t.          t          f$ r Y w xY wt          | t                    rt          d|  d| d          |t1          | j                  }|| fS )a  
    Select framework (TensorFlow or PyTorch) to use from the `model` passed. Returns a tuple (framework, model).

    If `model` is instantiated, this function will just infer the framework from the model class. Otherwise `model` is
    actually a checkpoint name and this method will try to instantiate it using `model_classes`. Since we don't want to
    instantiate the model twice, this model is returned for use by the pipeline.

    If both frameworks are installed and available for `model`, PyTorch is selected.

    Args:
        model (`str`, [`PreTrainedModel`] or [`TFPreTrainedModel`]):
            The model to infer the framework from. If `str`, a checkpoint name. The model to infer the framewrok from.
        config ([`AutoConfig`]):
            The config associated with the model to help using the correct class
        model_classes (dictionary `str` to `type`, *optional*):
            A mapping framework to class.
        task (`str`):
            The task defining which pipeline will be returned.
        model_kwargs:
            Additional dictionary of keyword arguments passed along to the model's `from_pretrained(...,
            **model_kwargs)` function.

    Returns:
        `Tuple`: A tuple framework, model.
    At least one of TensorFlow 2.0 or PyTorch should be installed. To install TensorFlow 2.0, read the instructions at https://www.tensorflow.org/install/ To install PyTorch, read the instructions at https://pytorch.org/._from_pipeliner1   >   Npt>   Ntfr{   r|   transformersNTFr   z2Pipeline cannot infer suitable model classes from z.h5Tfrom_tfz}Model might be a TensorFlow model (ending with `.h5`) but TensorFlow is not available. Trying to load the model with PyTorch.z.binfrom_ptz{Model might be a PyTorch model (ending with `.bin`) but PyTorch is not available. Trying to load the model with Tensorflow.evalzCould not load model z$ with any of the following classes: .)r   r   RuntimeErrorrJ   strgetr!   r   architectures	importlibimport_modulerp   appendtupler'   r(   copyendswithloggerwarningfrom_pretrainedhasattrr   OSErrorr   	__class__)modelrt   ru   rv   rw   model_kwargsclass_tuplelook_ptlook_tfclassesarchitecturetransformers_module_classmodel_classkwargss                  r*   infer_framework_load_modelr      s!   B  
%7%9%9 
Q
 
 	

 % 4p)-%&$&&D9+D!##A	\(A 	T R)M,=,=dYL,Q,QQ T)M,=,=d[N,S,SS 	7G & 4 	/ 	/&/&=n&M&M# /$%8,MMF)v... /$%8:M|:M:MtTTF)v...%g6K{q  YRWYYZZZ& 	 	K!&&((FD  U^^E%:%: $(y!=    d""u~~f'='="$(y!@  
33EDDVDD5&)) )!JJLLEZ(    eS!! 	pnUnn`knnnooo#EO44	es   42H((H<;H<c                     t          | t                    rt          j        | fd|i|}n| j        }t          | |f||||d|S )ar  
    Select framework (TensorFlow or PyTorch) to use from the `model` passed. Returns a tuple (framework, model).

    If `model` is instantiated, this function will just infer the framework from the model class. Otherwise `model` is
    actually a checkpoint name and this method will try to instantiate it using `model_classes`. Since we don't want to
    instantiate the model twice, this model is returned for use by the pipeline.

    If both frameworks are installed and available for `model`, PyTorch is selected.

    Args:
        model (`str`, [`PreTrainedModel`] or [`TFPreTrainedModel`]):
            The model to infer the framework from. If `str`, a checkpoint name. The model to infer the framewrok from.
        model_classes (dictionary `str` to `type`, *optional*):
            A mapping framework to class.
        task (`str`):
            The task defining which pipeline will be returned.
        model_kwargs:
            Additional dictionary of keyword arguments passed along to the model's `from_pretrained(...,
            **model_kwargs)` function.

    Returns:
        `Tuple`: A tuple framework, model.
    rz   )ru   rz   rv   rw   )rJ   r   r   r   rt   r   )r   ru   rv   rw   r   rt   s         r*   infer_framework_from_modelr     so    < % +EWW$W,WW%v%24d^g kw  r,   revisionc                 *   t          j        dt                     t                      st	                      st          d          t          | t                    rt	                      r%t                      st          j	        | |          } nqt                      r%t	                      st          j	        | |          } n>	 t          j	        | |          } n&# t          $ r t          j	        | |          } Y nw xY wt          | j                  }|S )a[  
    Select framework (TensorFlow or PyTorch) to use.

    Args:
        model (`str`, [`PreTrainedModel`] or [`TFPreTrainedModel`]):
            If both frameworks are installed, picks the one corresponding to the model passed (either a model class or
            the model name). If no specific model is provided, defaults to using PyTorch.
    zb`get_framework` is deprecated and will be removed in v5, use `infer_framework_from_model` instead.ry   )r   )warningswarnFutureWarningr   r   r   rJ   r   r!   r   r   r   r   r   )r   r   rw   s      r*   get_frameworkr   B  s>    Ml    
%7%9%9 
Q
 
 	

 % 	N 	N(9(9 	N-ehGGGEE 	N'9';'; 	N/IIIEEN!1%(KKK N N N#3EHMMMN  00Is   C  C<;C<targeted_tasktask_optionsreturnc                 6   t                      rt                      sd}nt                      rt                      sd}| d         }|r%||vrt          d|           ||         d         }n"d|v r| d         d         }nt          d          |d}||         S )a  
    Select a default model to use for a given task. Defaults to pytorch if ambiguous.

    Args:
        targeted_task (`Dict` ):
           Dictionary representing the given task, that should contain default models

        framework (`str`, None)
           "pt", "tf" or None, representing a specific framework if it was specified, or None if we don't know yet.

        task_options (`Any`, None)
           Any further value required by the task to get fully specified, for instance (SRC, TGT) languages for
           translation task.

    Returns

        `str` The model string representing the default model for this pipeline
    r{   r|   defaultz9The task does not provide any default models for options r   zXThe task defaults can't be correctly selected. You probably meant "translation_XX_to_YY")r   r   r(   )r   rw   r   defaultsdefault_modelss        r*   get_default_model_and_revisionr   d  s    *  O$5$5 					 #5#7#7 	Y'H 	vx''gYegghhh!,/8	H		&y1': tuuu	)$$r,   c                   0     e Zd ZdZdededef fdZ xZS )PipelineExceptionz
    Raised by a [`Pipeline`] when handling __call__.

    Args:
        task (`str`): The task of the pipeline.
        model (`str`): The model used by the pipeline.
        reason (`str`): The error message to display.
    rv   r   reasonc                 f    t                                          |           || _        || _        d S N)super__init__rv   r   )selfrv   r   r   r   s       r*   r   zPipelineException.__init__  s-       	


r,   )__name__
__module____qualname____doc__r   r   __classcell__r   s   @r*   r   r     s\         S  c          r,   r   c                   (    e Zd ZdZed             ZdS )ArgumentHandlerzQ
    Base interface for handling arguments for each [`~pipelines.Pipeline`].
    c                     t                      r   NotImplementedError)r   argsr   s      r*   __call__zArgumentHandler.__call__      !###r,   N)r   r   r   r   r   r   r1   r,   r*   r   r     s9          $ $ ^$ $ $r,   r   c                   (   e Zd ZdZg dZ	 ddee         dee         dee         defdZe	d	             Z
e	d
eeee         f         fd            Zd
eeee         f         defdZe	 ddedee         dee         dee         dd f
d            ZdS )PipelineDataFormata  
    Base class for all the pipeline supported data format both for reading and writing. Supported data formats
    currently includes:

    - JSON
    - CSV
    - stdin/stdout (pipe)

    `PipelineDataFormat` also includes some utilities to work with multi-columns like mapping from datasets columns to
    pipelines keyword arguments through the `dataset_kwarg_1=dataset_column_1` format.

    Args:
        output_path (`str`, *optional*): Where to save the outgoing data.
        input_path (`str`, *optional*): Where to look for the input data.
        column (`str`, *optional*): The column to read.
        overwrite (`bool`, *optional*, defaults to `False`):
            Whether or not to overwrite the `output_path`.
    )jsoncsvpipeFoutput_path
input_pathcolumn	overwritec                    || _         || _        ||                    d          ndg| _        t	          | j                  dk    | _        | j        rd | j        D             | _        |:|s8t          t          | j                             rt          | j          d          |8t          t          | j                            st          | j         d          d S d S )N, r"   c                 b    g | ],}d |v r"t          |                    d                     n||f-S )=)r   splitr3   cs     r*   r6   z/PipelineDataFormat.__init__.<locals>.<listcomp>  s;    \\\1#((5...A\\\r,   z already exists on diskz doesnt exist on disk)	r   r   r   r   r'   is_multi_columnsr   r   r   )r   r   r   r   r   s        r*   r   zPipelineDataFormat.__init__  s     '$+1+=fll3'''B4 #DK 0 01 4  	]\\PTP[\\\DK"9"gd.//00 L!1JJJKKK!'$/2233 IGGGHHH "!I Ir,   c                     t                      r   r   r   s    r*   __iter__zPipelineDataFormat.__iter__  r   r,   datac                     t                      )z
        Save the provided data object with the representation for the current [`~pipelines.PipelineDataFormat`].

        Args:
            data (`dict` or list of `dict`): The data to store.
        r   r   r   s     r*   savezPipelineDataFormat.save  s     "###r,   r   c                    t           j                            | j                  \  }}t           j        j                            |df          }t          |d          5 }t          j        ||           ddd           n# 1 swxY w Y   |S )z
        Save the provided data object as a pickle-formatted binary data on the disk.

        Args:
            data (`dict` or list of `dict`): The data to store.

        Returns:
            `str`: Path where the data has been saved.
        picklezwb+N)	ospathsplitextr   extsepjoinopenr   dump)r   r   r   _binary_pathf_outputs         r*   save_binaryzPipelineDataFormat.save_binary  s     '""4#344agn))4*:;;+u%% 	(Kh'''	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( s   B  BBformatc                     | dk    rt          ||||          S | dk    rt          ||||          S | dk    rt          ||||          S t          d|  d          )a  
        Creates an instance of the right subclass of [`~pipelines.PipelineDataFormat`] depending on `format`.

        Args:
            format (`str`):
                The format of the desired pipeline. Acceptable values are `"json"`, `"csv"` or `"pipe"`.
            output_path (`str`, *optional*):
                Where to save the outgoing data.
            input_path (`str`, *optional*):
                Where to look for the input data.
            column (`str`, *optional*):
                The column to read.
            overwrite (`bool`, *optional*, defaults to `False`):
                Whether or not to overwrite the `output_path`.

        Returns:
            [`~pipelines.PipelineDataFormat`]: The proper data format.
        r   r   r   r   zUnknown reader z% (Available reader are json/csv/pipe))JsonPipelineDataFormatCsvPipelineDataFormatPipedPipelineDataFormatKeyError)r   r   r   r   r   s        r*   from_strzPipelineDataFormat.from_str  s    4 V)+z6U^____u__(j&T]^^^^v*;
FV_````ZVZZZ[[[r,   NF)r   r   r   r   SUPPORTED_FORMATSr   r   boolr   r   r   r   dictr   r   r   staticmethodr   r1   r,   r*   r   r     su        & 0//  I Ic]I SMI 	I
 I I I I. $ $ ^$ $tT$Z/0 $ $ $ ^$dDJ&6 7 C    $   \  \ \c] \ SM \ 	 \ 
 \  \  \ \ \  \  \r,   r   c                   v     e Zd ZdZ	 d
dee         dee         dee         f fdZd Zdee	         fd	Z
 xZS )r   a  
    Support for pipelines using CSV data format.

    Args:
        output_path (`str`, *optional*): Where to save the outgoing data.
        input_path (`str`, *optional*): Where to look for the input data.
        column (`str`, *optional*): The column to read.
        overwrite (`bool`, *optional*, defaults to `False`):
            Whether or not to overwrite the `output_path`.
    Fr   r   r   c                 R    t                                          ||||           d S )Nr   )r   r   )r   r   r   r   r   r   s        r*   r   zCsvPipelineDataFormat.__init__(  s,     	j&INNNNNr,   c              #      K   t          | j        d          5 }t          j        |          }|D ]4| j        rfd| j        D             V  | j        d                  V  5	 d d d            d S # 1 swxY w Y   d S )Nrc                 (    i | ]\  }}||         S r1   r1   )r3   kr   rows      r*   
<dictcomp>z2CsvPipelineDataFormat.__iter__.<locals>.<dictcomp>6  s#    ===A1c!f===r,   r   )r   r   r   
DictReaderr   r   )r   freaderr   s      @r*   r   zCsvPipelineDataFormat.__iter__1  s      $/3'' 	.1^A&&F . .( .===========dk!n-----	.	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	.s   AA33A7:A7r   c                 N   t          | j        d          5 }t          |          dk    rct          j        |t          |d                                                             }|                                 |                    |           ddd           dS # 1 swxY w Y   dS )z
        Save the provided data object with the representation for the current [`~pipelines.PipelineDataFormat`].

        Args:
            data (`List[dict]`): The data to store.
        wr   N)	r   r   r'   r   
DictWriterlistrg   writeheader	writerows)r   r   r  writers       r*   r   zCsvPipelineDataFormat.save:  s     $"C(( 	'A4yy1}}4Q+?+?@@""$$$  &&&		' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	's   A7BB!Br   )r   r   r   r   r   r   r   r   r   r   r   r   r   s   @r*   r   r     s        	 	  O Oc]O SMO 	O O O O O O. . .'d ' ' ' ' ' ' ' 'r,   r   c                   j     e Zd ZdZ	 d
dee         dee         dee         f fdZd Zdefd	Z	 xZ
S )r   a  
    Support for pipelines using JSON file format.

    Args:
        output_path (`str`, *optional*): Where to save the outgoing data.
        input_path (`str`, *optional*): Where to look for the input data.
        column (`str`, *optional*): The column to read.
        overwrite (`bool`, *optional*, defaults to `False`):
            Whether or not to overwrite the `output_path`.
    Fr   r   r   c                     t                                          ||||           t          |d          5 }t          j        |          | _        d d d            d S # 1 swxY w Y   d S )Nr   r   )r   r   r   r   load_entries)r   r   r   r   r   r  r   s         r*   r   zJsonPipelineDataFormat.__init__T  s     	j&INNN*c"" 	)a IaLLDM	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	)s   AA"%A"c              #      K   | j         D ]4| j        rfd| j        D             V  | j        d                  V  5d S )Nc                 (    i | ]\  }}||         S r1   r1   )r3   r   r   entrys      r*   r   z3JsonPipelineDataFormat.__iter__.<locals>.<dictcomp>c  s#    ;;;tq!q%(;;;r,   r   )r  r   r   )r   r  s    @r*   r   zJsonPipelineDataFormat.__iter__`  sl      ] 	, 	,E$ ,;;;;t{;;;;;;;DKN+++++		, 	,r,   r   c                     t          | j        d          5 }t          j        ||           ddd           dS # 1 swxY w Y   dS )z|
        Save the provided data object in a json file.

        Args:
            data (`dict`): The data to store.
        r  N)r   r   r   r   )r   r   r  s      r*   r   zJsonPipelineDataFormat.saveg  s     $"C(( 	AIdA	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   9= =r   )r   r   r   r   r   r   r   r   r   r   r   r   s   @r*   r   r   H  s        	 	  
) 
)c]
) SM
) 	
) 
) 
) 
) 
) 
), , ,        r,   r   c                   Z     e Zd ZdZd ZdefdZdeeee         f         de	f fdZ
 xZS )r   a  
    Read data from piped input to the python process. For multi columns data, columns should separated by 	

    If columns are provided, then the output will be a dictionary with {column_x: value_x}

    Args:
        output_path (`str`, *optional*): Where to save the outgoing data.
        input_path (`str`, *optional*): Where to look for the input data.
        column (`str`, *optional*): The column to read.
        overwrite (`bool`, *optional*, defaults to `False`):
            Whether or not to overwrite the `output_path`.
    c              #      K   t           j        D ]Z}d|v rP|                    d          }| j        r"d t	          | j        |          D             V  Dt          |          V  V|V  [d S )N	c                      i | ]\  \  }}}||S r1   r1   )r3   r   r   ls       r*   r   z4PipedPipelineDataFormat.__iter__.<locals>.<dictcomp>  s"    RRR&!a61RRRr,   )sysstdinr   r   zipr   )r   lines     r*   r   z PipedPipelineDataFormat.__iter__  s      I 	 	Dt||zz$''; &RR3t{D;Q;QRRRRRRR++%%%% 



	 	r,   r   c                 $    t          |           dS )z^
        Print the data.

        Args:
            data (`dict`): The data to store.
        N)printr   s     r*   r   zPipedPipelineDataFormat.save  s     	dr,   r   c                 r    | j         t          d          t                                          |          S )NzWhen using piped input on pipeline outputting large object requires an output file path. Please provide such output path through --output argument.)r   r   r   r   )r   r   r   s     r*   r   z#PipedPipelineDataFormat.save_binary  s>    #M  
 ww""4(((r,   )r   r   r   r   r   r   r   r   r   r   r   r   r   s   @r*   r   r   r  s               )dDJ&6 7 )C ) ) ) ) ) ) ) ) ) )r,   r   c                   >    e Zd ZdZed             Zed             ZdS )_ScikitCompatzA
    Interface layer for the Scikit and Keras compatibility.
    c                     t                      r   r   r   Xs     r*   	transformz_ScikitCompat.transform  r   r,   c                     t                      r   r   r!  s     r*   predictz_ScikitCompat.predict  r   r,   N)r   r   r   r   r   r#  r%  r1   r,   r*   r  r    sT          $ $ ^$ $ $ ^$ $ $r,   r  a	  
    Arguments:
        model ([`PreTrainedModel`] or [`TFPreTrainedModel`]):
            The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from
            [`PreTrainedModel`] for PyTorch and [`TFPreTrainedModel`] for TensorFlow.
        tokenizer ([`PreTrainedTokenizer`]):
            The tokenizer that will be used by the pipeline to encode data for the model. This object inherits from
            [`PreTrainedTokenizer`].
        modelcard (`str` or [`ModelCard`], *optional*):
            Model card attributed to the model for this pipeline.
        framework (`str`, *optional*):
            The framework to use, either `"pt"` for PyTorch or `"tf"` for TensorFlow. The specified framework must be
            installed.

            If no framework is specified, will default to the one currently installed. If no framework is specified and
            both frameworks are installed, will default to the framework of the `model`, or to PyTorch if no model is
            provided.
        task (`str`, defaults to `""`):
            A task-identifier for the pipeline.
        num_workers (`int`, *optional*, defaults to 8):
            When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the number of
            workers to be used.
        batch_size (`int`, *optional*, defaults to 1):
            When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the size of
            the batch to use, for inference this is not always beneficial, please read [Batching with
            pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) .
        args_parser ([`~pipelines.ArgumentHandler`], *optional*):
            Reference to the object in charge of parsing supplied pipeline parameters.
        device (`int`, *optional*, defaults to -1):
            Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on
            the associated CUDA device id. You can pass native `torch.device` or a `str` too.
        binary_output (`bool`, *optional*, defaults to `False`):
            Flag indicating if the output the pipeline should happen in a binary format (i.e., pickle) or as raw text.
)PipelineChunkIteratorPipelineDatasetPipelineIteratorPipelinePackIteratorc                      e Zd ZdZdZ	 	 	 	 	 	 	 	 	 	 d3ded         dee         dee         d	ee	         d
ee
         dee         dededeedf         deeedf                  defdZd4dedefdZd Zd Zed             Zd Zd Zdeee         ef         fdZed             Zeded ed!eeef         fd"            Zed#eeef         d$ed!e fd%            Z!ed&e d'ed!efd(            Z"d) Z#d* Z$d+ed,efd-Z%ddd.d/Z&d0 Z'd1 Z(d2 Z)dS )5Pipelinea  
    The Pipeline class is the class from which all pipelines inherit. Refer to this class for methods shared across
    different pipelines.

    Base class implementing pipelined operations. Pipeline workflow is defined as a sequence of the following
    operations:

        Input -> Tokenization -> Model Inference -> Post-Processing (task dependent) -> Output

    Pipeline supports running on CPU or GPU through the device argument (see below).

    Some pipeline, like for instance [`FeatureExtractionPipeline`] (`'feature-extraction'`) output large tensor object
    as nested-lists. In order to avoid dumping such large structure as textual data we provide the `binary_output`
    constructor argument. If set to `True`, the output will be stored in the pickle format.
    Nr   Fr   )r%   r$   rm   rk   image_processor	modelcardrw   rv   args_parserdeviceztorch.devicetorch_dtypeztorch.dtypebinary_outputc                    |t          ||j                  \  }}|| _        || _        || _        || _        || _        || _        || _        t          | j        dd           }||	t          d          | j        dk    r7|	5t          |	t                    r|	dk     s| j                            |	           |	3|/t          t          |                                                    }	nd}	t#                      r| j        dk    rt          |	t$          j                  r|	| _        nwt          |	t(                    rt%          j        |	          | _        nH|	dk     rt%          j        d          | _        n(t%          j        d|	           | _        n|	|	nd| _        |
| _        || _        | j        j        j        }|y||v ru| j        j                            |                    |                     | j                                        r* | j        j        j        di |                    |           d| _        |                    d	d           | _        |                    d
d           | _         | j         di |\  | _!        | _"        | _#        | j        /| j        *t          | j        tH                    r| j        | _        d S d S d S d S )N)rt   hf_device_mapzThe model has been loaded with `accelerate` and therefore cannot be moved to a specific device. Please discard the `device` argument when creating your pipeline object.r{   r   rF   cpuzcuda:rU   num_workersr1   )%r   rt   rv   r   rm   rk   r,  r-  rw   rp   r(   rJ   inttonextitervaluesr   rK   r/  r   r0  r1  task_specific_paramsupdater   can_generategeneration_config
call_countpop_batch_size_num_workers_sanitize_parameters_preprocess_params_forward_params_postprocess_paramsr   )r   r   rm   rk   r,  r-  rw   rv   r.  r/  r0  r1  r   r3  r;  s                  r*   r   zPipeline.__init__  s    9%UUUIu	
"!2.""  
OTBB$);T   >T!!f&8*VUXBYBY&8^dgh^h^hJMM&!!!>(d=#7#7#9#9::;; 
	?DNd$:$:&%,// =$FC(( =#l622!#l511#l+;6+;+;<<$*$6&&BDK&*  $z0E+8L0L0LJ$$%9%=%=d%C%CDDDz&&(( V3
,3UU6J6N6Nt6T6TUUU!::lD99"JJ}d;;RkRVRkRuRuntRuRuO!5t7O'D,B,N$02DEE > (,'=$$$ (',N,N> >r,   save_directorysafe_serializationc                    t           j                            |          r t                              d| d           dS t          j        |d           t          | d          r| j                                        }i }|	                                D ]\  }}|d         | j
        k    r|                                }|d         j        }|                    d          d	         }| d|d         j         |d<   t          d
 |d         D                       |d<   t          d |d         D                       |d<   |||<   || j        j        _        t%          | |           | j                            ||           | j        | j                            |           | j        | j                            |           | j        | j                            |           dS dS )ad  
        Save the pipeline's model and tokenizer.

        Args:
            save_directory (`str`):
                A path to the directory where to saved. It will be created if it doesn't exist.
            safe_serialization (`str`):
                Whether to save the model using `safetensors` or the traditional way for PyTorch or Tensorflow
        zProvided path (z#) should be a directory, not a fileNT)exist_ok_registered_implimplr   rF   c              3   $   K   | ]}|j         V  d S r   r   r   s     r*   r@   z+Pipeline.save_pretrained.<locals>.<genexpr>[  $      "B"B!1:"B"B"B"B"B"Br,   r{   c              3   $   K   | ]}|j         V  d S r   rN  r   s     r*   r@   z+Pipeline.save_pretrained.<locals>.<genexpr>\  rO  r,   r|   )rH  )r   r   isfiler   errormakedirsr   rK  r   r)   r   r   r   r   r   r   rt   custom_pipelinesr   save_pretrainedrm   rk   r-  )	r   rG  rH  pipeline_inforT  rv   infomodule_namelast_modules	            r*   rU  zPipeline.save_pretrained?  s    7>>.)) 	LL^>^^^___F
NT22224+,, 	5 16688M!+1133 . .
d<4>11yy{{"6l5)//44R8"-GGV0EGGV""B"BtDz"B"B"BBBT
""B"BtDz"B"B"BBBT
)- &&1ADJ.t^444
"">FX"YYY>%N**>:::!-"22>BBB>%N**>::::: &%r,   c                      | |          S zn
        Scikit / Keras interface to transformers' pipelines. This method will forward to __call__().
        r1   r!  s     r*   r#  zPipeline.transformn       tAwwr,   c                      | |          S r[  r1   r!  s     r*   r%  zPipeline.predictt  r\  r,   c              #   ^  K   | j         dk    rHt          j        | j        dk    rdn	d| j                   5  dV  ddd           dS # 1 swxY w Y   dS | j        j        dk    rCt          j                            | j                  5  dV  ddd           dS # 1 swxY w Y   dS dV  dS )a  
        Context Manager allowing tensor allocation on the user-specified device in framework agnostic way.

        Returns:
            Context manager

        Examples:

        ```python
        # Explicitly ask for tensor allocation on CUDA device :0
        pipe = pipeline(..., device=0)
        with pipe.device_placement():
            # Every framework specific tensor allocation will be done on the request device
            output = pipe(...)
        ```r|   rF   z/CPU:0z/device:GPU:Ncuda)rw   r|   r/  typerK   r_  r   s    r*   device_placementzPipeline.device_placementz  sS     " >T!!t{b'8'888>ZT[>Z>Z[[                    {6))Z&&t{33  EEE                  s#   A		AA
BB #B c                 8    |                      || j                  S )av  
        Ensure PyTorch tensors are on the specified device.

        Args:
            inputs (keyword arguments that should be `torch.Tensor`, the rest is ignored):
                The tensors to place on `self.device`.
            Recursive on lists **only**.

        Return:
            `Dict[str, torch.Tensor]`: The same as `inputs` but on the proper device.
        )_ensure_tensor_on_devicer/  )r   inputss     r*   ensure_tensor_on_devicez Pipeline.ensure_tensor_on_device  s     ,,VT[AAAr,   c                      t          |t                    r.t           fd|                                D                       S t          |t                    r! fd|                                D             S t          |t                    r.t	           fd|                                D                       S t          |t
                    r fd|D             S t          |t                    rt           fd|D                       S t          |t          j                  r`t          j	        d          k    r3|j
        t          j        t          j        hv r|                                }|                              S |S )Nc                 D    i | ]\  }}|                     |          S r1   rc  r3   namerX   r/  r   s      r*   r   z5Pipeline._ensure_tensor_on_device.<locals>.<dictcomp>  s/    hhhvt44VVDDhhhr,   c                 D    i | ]\  }}|                     |          S r1   rh  ri  s      r*   r   z5Pipeline._ensure_tensor_on_device.<locals>.<dictcomp>  s0    kkkLDRXD$77GGkkkr,   c                 D    i | ]\  }}|                     |          S r1   rh  ri  s      r*   r   z5Pipeline._ensure_tensor_on_device.<locals>.<dictcomp>  s2    tttUaUY[aT4#@#@#P#Ptttr,   c                 <    g | ]}                     |          S r1   rh  r3   r4   r/  r   s     r*   r6   z5Pipeline._ensure_tensor_on_device.<locals>.<listcomp>  s)    SSSDD11$??SSSr,   c                 <    g | ]}                     |          S r1   rh  rn  s     r*   r6   z5Pipeline._ensure_tensor_on_device.<locals>.<listcomp>  s)    YYY$$77fEEYYYr,   r4  )rJ   r   r)   r   r   r  r   rK   rL   r/  rD   float16bfloat16floatr7  )r   rd  r/  s   ` `r*   rc  z!Pipeline._ensure_tensor_on_device  s   fk** 	hhhhhY_YeYeYgYghhh   %% 	kkkkk\b\h\h\j\jkkkk)) 	tttttekeqeqesestttuuu%% 		SSSSSFSSSS&& 	YYYYYRXYYYZZZ-- 	e,,,,%-QVQ_A`1`1`99V$$$Mr,   supported_modelsc           	         t          |t                    sg }|                                D ]R\  }}t          |t                    r#|                    t          |                     =|                    |           St          |d          rs|j        j                                        D ]T\  }}t          |t                    r |                    d |D                        :|                    |j	                   U|}| j
        j        j	        |vr:t                              d| j
        j        j	         d| j         d| d           dS dS )z
        Check if the model class is in supported by the pipeline.

        Args:
            supported_models (`List[str]` or `dict`):
                The list of models supported by the pipeline, or a dictionary with model class values.
        _model_mappingc                     g | ]	}|j         
S r1   rN  )r3   ms     r*   r6   z-Pipeline.check_model_type.<locals>.<listcomp>  s    6Q6Q6Qaqz6Q6Q6Qr,   zThe model 'z' is not supported for z. Supported models are r   N)rJ   r  r)   r   extendr   r   ru  _extra_contentr   r   r   r   rR  rv   )r   rs  supported_models_namesr   
model_namer   s         r*   check_model_typezPipeline.check_model_type  s    *D11 	6%'"!1!7!7!9!9 > >:j%00 >*11$z2B2BCCCC*11*====')9:: F 0 ? N T T V V F FHAu!*e44 F.556Q6Q56Q6Q6QRRRR.55enEEEE5:(0@@@LL(dj2; ( (TXT] ( ($( ( (     A@r,   c                      t          d          )aG  
        _sanitize_parameters will be called with any excessive named arguments from either `__init__` or `__call__`
        methods. It should return 3 dictionnaries of the resolved parameters used by the various `preprocess`,
        `forward` and `postprocess` methods. Do not fill dictionnaries if the caller didn't specify a kwargs. This
        let's you keep defaults in function signatures, which is more "natural".

        It is not meant to be called directly, it will be automatically called and the final parameters resolved by
        `__init__` and `__call__`
        z$_sanitize_parameters not implementedr   )r   pipeline_parameterss     r*   rC  zPipeline._sanitize_parameters  s     ""HIIIr,   input_preprocess_parametersr   c                      t          d          )z
        Preprocess will take the `input_` of a specific pipeline and return a dictionary of everything necessary for
        `_forward` to run properly. It should contain at least one tensor, but might have arbitrary other items.
        zpreprocess not implementedr   )r   r  r  s      r*   
preprocesszPipeline.preprocess  s     "">???r,   input_tensorsforward_parametersc                      t          d          )a  
        _forward will receive the prepared dictionary from `preprocess` and run it on the model. This method might
        involve the GPU or the CPU and should be agnostic to it. Isolating this function is the reason for `preprocess`
        and `postprocess` to exist, so that the hot path, this method generally can run as fast as possible.

        It is not meant to be called directly, `forward` is preferred. It is basically the same but contains additional
        code surrounding `_forward` making sure tensors and models are on the same device, disabling the training part
        of the code (leading to faster inference).
        z_forward not implementedr   )r   r  r  s      r*   _forwardzPipeline._forward  s     ""<===r,   model_outputspostprocess_parametersc                      t          d          )a  
        Postprocess will receive the raw outputs of the `_forward` method, generally tensors, and reformat them into
        something more friendly. Generally it will output a list or a dict or results (containing just strings and
        numbers).
        zpostprocess not implementedr   )r   r  r  s      r*   postprocesszPipeline.postprocess  s     ""?@@@r,   c                     t           j        S r   )rK   no_gradr   s    r*   get_inference_contextzPipeline.get_inference_context  s
    }r,   c                    |                                  5  | j        dk    rd|d<    | j        |fi |}n| j        dk    r|                                 } |            5  |                     || j                  } | j        |fi |}|                     |t          j        d                    }d d d            n# 1 swxY w Y   nt          d| j         d          d d d            n# 1 swxY w Y   |S )	Nr|   Ftrainingr{   )r/  r4  z
Framework z is not supported)ra  rw   r  r  rc  r/  rK   r(   )r   model_inputsforward_paramsr  inference_contexts        r*   forwardzPipeline.forward  s   ""$$ 	Q 	Q~%%+0Z( -l M Mn M M4''$($>$>$@$@!&&(( m m#'#@#@VZVa#@#b#bL$1DM,$Q$Q.$Q$QM$($A$A-X]XdejXkXk$A$l$lMm m m m m m m m m m m m m m m
 !!Odn!O!O!OPPP	Q 	Q 	Q 	Q 	Q 	Q 	Q 	Q 	Q 	Q 	Q 	Q 	Q 	Q 	Q s7   A	C.AB>2C.>C	C.C	C..C25C2r5  rU   c                 @   t          |t          j        j                  rt	          || j        |          }n8|dk    rt                              d           d}t          || j        |          }dt          j
        vr)t                              d           dt          j
        d<   | j        | j        n| j        }|dk    rt          nt          | j        |          }	t#          ||||	          }
t          |
| j        ||          }t          || j        |          }|S )Nr"   zFor iterable dataset using num_workers>1 is likely to result in errors since everything is iterable, setting `num_workers=1` to guarantee correctness.TOKENIZERS_PARALLELISMNDisabling tokenizer parallelism, we're using DataLoader multithreading alreadyfalser5  rU   
collate_fnloader_batch_size)rJ   collectionsabcSizedr'  r  r   r   r(  r   environrW  rk   r,  r+   rs   rm   r   r  r  r   rd  r5  rU   preprocess_paramsr  postprocess_paramsdatasetrk   r  
dataloadermodel_iteratorfinal_iterators                r*   get_iteratorzPipeline.get_iterator  s!    fko344 
	S%fdo?PQQGGQ1  
  &vt@QRRG#2:55KKhiii3:BJ/06:6L6XD22^b^r&0Aoo]]>$.Zk;l;l
[Zdnooo
)*dlNfpqqq).$:JL^__r,   )r5  rU   c                ,   |rt                               d|            || j        d}n| j        }|| j        d}n| j        } | j        di |\  }}}i | j        |}i | j        |}i | j        |}| xj        dz  c_        | j        dk    r5| j	        dk    r*| j
        j        dk    rt          j        dt                     t          d uot!          |t                    }	t!          |t"          j                  }
t!          |t&                    }|	p|
p|}| j	        dk    o|	p|
p|}|rE|r+|                     ||||||          }t'          |          }|S |                     ||||          S |r|                     ||||||          S |r|                     ||||          S | j	        dk    rJt!          | t.                    r5t1          t3          |                     |g|||||                              S |                     ||||          S )	NzIgnoring args : r   r"   
   r{   r_  zlYou seem to be using the pipelines sequentially on GPU. In order to maximize efficiency please use a datasetr1   )r   r   rB  rA  rC  rD  rE  rF  r?  rw   r/  r`  r   r   UserWarningr    rJ   typesGeneratorTyper  r  	run_multiiterateChunkPipeliner8  r9  
run_single)r   rd  r5  rU   r   r   r  r  r  
is_datasetis_generatoris_listis_iterablecan_use_iteratorr  outputss                   r*   r   zPipeline.__call__*  s    	6NN4d44555 ("/'

!-
@Y@Y@c@c\b@c@c=>+= Mt6L:KLCD0CNCO 8O<NO1?RDNd$:$:t{?OSY?Y?YM   D(HZ-H-H
!&%*=>>VT** ;L;G  >T1]z7\\7\U\ 	b e!%!2!2K5FXj" " ~..~~f.?Qcddd 	b$$Z1BNTf    	b<<(9>K]^^^^t##
4(G(G#%%+z;Ln^p     ??6+<nN`aaar,   c                 ,      fd|D             S )Nc                 @    g | ]}                     |          S r1   r  )r3   r4   r  r  r  r   s     r*   r6   z&Pipeline.run_multi.<locals>.<listcomp>l  s.    pppae&7I[\\pppr,   r1   )r   rd  r  r  r  s   ` ```r*   r  zPipeline.run_multik  s*    pppppppioppppr,   c                 Z     | j         |fi |} | j        |fi |} | j        |fi |}|S r   )r  r  r  )r   rd  r  r  r  r  r  r  s           r*   r  zPipeline.run_singlen  sU    &tvCC1BCC$\DD^DD"$"=GG4FGGr,   c              #   H   K   |D ]}|                      ||||          V  d S r   r  )r   rd  r  r  r  r  s         r*   r  zPipeline.iteratet  sH        	a 	aF//&*;^M_``````	a 	ar,   )
NNNNNr   NNNFr   )*r   r   r   r   default_input_namesr   r   r   r   r   r   r   r   r6  r   r   rU  r#  r%  r   ra  re  rc  r   r   r|  r   rC  r
   r   r   r  r   r  r  r  r  r  r   r  r  r  r1   r,   r*   r+  r+    sA          
 48BF8<)-#''+-1;?#M> M>;<M> /0M> $$>?	M>
 ""45M> I&M> C=M> M> %M> c>)*M> eC$678M> M> M> M> M>^-; -;c -;t -; -; -; -;^       ^4B B B  (tCy$1G    : 
J 
J ^
J @ @t @SR_M_H` @ @ @ ^@ 
>d3+=&> 
>VZ 
>_j 
> 
> 
> ^
> A APT AY\ A A A ^A    #&47   2 374 ?b ?b ?b ?b ?bBq q q  a a a a ar,   r+  c                   $    e Zd Zd ZdedefdZdS )r  c                     g } | j         |fi |D ]%} | j        |fi |}|                    |           & | j        |fi |}|S r   )r  r  r   r  )	r   rd  r  r  r  all_outputsr  r  r  s	            r*   r  zChunkPipeline.run_single|  s{    +DOFHH6GHH 	. 	.L(DLHHHHM}----"$";EE2DEEr,   r5  rU   c                    dt           j        vr)t                              d           dt           j        d<   |dk    rt                              d           d}t          || j        |          }| j        | j        n| j        }|dk    rt          nt          | j        |          }	t          ||||	          }
t          |
| j        ||          }t          || j        |          }|S )Nr  r  r  r"   zFor ChunkPipeline using num_workers>0 is likely to result in errors since everything is iterable, setting `num_workers=1` to guarantee correctness.r  r  )r   r  r   rW  r   r&  r  rk   r,  r+   rs   rm   r   r)  r  r(  r  r  s                r*   r  zChunkPipeline.get_iterator  s     $2:55KKhiii3:BJ/0??NNE   K'ARSS 7;6L6XD22^b^r&0Aoo]]>$.Zk;l;l
[Zdnooo
-j$,jtuuu).$:JL^__r,   N)r   r   r   r  r6  r  r1   r,   r*   r  r  {  sG          #&47     r,   r  c                      e Zd Zdeeef         deeef         ddfdZdee         fdZdede	eeef         fdZ
	 	 	 	 dded	ed
eeee	e         f                  deeee	e         f                  dee         dee         ddfdZd ZdS )PipelineRegistrysupported_taskstask_aliasesr   Nc                 "    || _         || _        d S r   )r  r  )r   r  r  s      r*   r   zPipelineRegistry.__init__  s    .(r,   c                     t          | j                                                  t          | j                                                  z   }|                                 |S r   )r  r  rg   r  sort)r   supported_tasks     r*   get_supported_tasksz$PipelineRegistry.get_supported_tasks  sR    d27799::T$BSBXBXBZBZ=[=[[r,   rv   c                    || j         v r| j         |         }|| j        v r| j        |         }||d fS |                    d          ru|                    d          }t	          |          dk    r:|d         dk    r.|d         dk    r"| j        d         }d}|||d         |d         ffS t          d	| d
          t          d| d|                                 dgz              )Ntranslationr   r9   r   r   r7  r"   rE   zInvalid translation task z#, use 'translation_XX_to_YY' formatzUnknown task z, available tasks are translation_XX_to_YY)r  r  
startswithr   r'   r   r  )r   rv   r   tokenss       r*   
check_taskzPipelineRegistry.check_task  s   4$$$$T*D4''' 06M,,??=)) 	bZZ__F6{{aF1I$>$>6!9PTCTCT $ 4] C$]VAYq	,BBB`t```aaaoDoo8P8P8R8RVlUm8moo
 
 	
r,   pipeline_classpt_modeltf_modelr   r`  c                 :   || j         v r t                              | d| d           |d}nt          |t                    s|f}|d}nt          |t                    s|f}|||d}|d|vrd|v sd|v rd|i}||d<   |||d	<   || j         |<   ||i|_        d S )
Nz6 is already registered. Overwriting pipeline for task z...r1   )rL  r{   r|   r   r{   r|   r   r`  )r  r   r   rJ   r   rK  )r   rv   r  r  r  r   r`  	task_impls           r*   register_pipelinez"PipelineRegistry.register_pipeline  s     4'''NNdccZ^cccdddHHHe,, 	# {HHHHe,, 	# {H+88LL	g%%47??dgoo"G,#*Ii  $If%.T"+/*;'''r,   c                     | j         S r   )r  r   s    r*   to_dictzPipelineRegistry.to_dict  s    ##r,   )NNNN)r   r   r   r   r   r
   r   r   r  r   r  r`  r   r   r  r  r1   r,   r*   r  r    sD       )S#X )d3PS8n )Y] ) ) ) )T#Y    

s 
uS$^'< 
 
 
 
. 8<7;"&"!< !<!< !< 5uT{!234	!<
 5uT{!234!< $!< sm!< 
!< !< !< !<F$ $ $ $ $r,   r  )NNNr   )[r  r   r   r   r   r   r  r  r   r  r   r   r   
contextlibr   os.pathr   r   typingr	   r
   r   r   r   r   r   dynamic_module_utilsr   feature_extraction_utilsr   image_processing_utilsr   r-  r   models.auto.configuration_autor   tokenization_utilsr   utilsr   r   r   r   r   r   r   
tensorflowr|   models.auto.modeling_tf_autor   rK   torch.utils.datar   r    models.auto.modeling_autor!   pt_utilsr#   modeling_tf_utilsr$   modeling_utilsr%   
get_loggerr   r   r+   rZ   rs   r   r`  r   r   r   r   	Exceptionr   r   r   r   r   r   r  PIPELINE_INIT_ARGStransformers.pipelines.pt_utilsr&  r'  r(  r)  r+  r  r  r1   r,   r*   <module>r     s+       



      				  



   # # # # # # # #             % % % % % % # # # # # # # # I I I I I I I I I I I I I I I I I I 5 5 5 5 5 5 A A A A A A 7 7 7 7 7 7 ! ! ! ! ! ! 7 7 7 7 7 7 4 4 4 4 4 4 r r r r r r r r r r r r r r r r d?+^[HI? ;:::::: 
LLL44444444555555 %$$$$$$GJ 1555555000000 
	H	%	%  /- /- /-d< < <D 7;#_ __ DeDk!123_ 3-	_
 }_ _ _ _H 7;#	$ $DeDk!123$ 3-$ }	$ $ $ $N 8C=    D)%)%$,SM)%AI#)%
3c3h )% )% )% )%X    	   "$ $ $ $ $c $ $ $n\ n\ n\ n\ n\ n\ n\ n\b)' )' )' )' )'. )' )' )'X' ' ' ' '/ ' ' 'T-) -) -) -) -)0 -) -) -)`$ $ $ $ $C $ $ $! F              &''[a [a [a [a [a} [a [a ('[a|    H   @A$ A$ A$ A$ A$ A$ A$ A$ A$ A$r,   