o
    h                     @   s>  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	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%m&Z& ddl'm(Z( ddl)m*Z* ddl+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z: eed ddf Z;e1 rd dl<Z=ddl>m?Z? e2 rd dl@Z@d dlAmBZBmCZC ddlDmEZE ddlFmGZG ddlHmIZI ndZCdZIerddlJmKZK ddlDmEZE e:LeMZNdd ZOdd ZPdd ZQ			d\d e%d!eeeReeS f  d"eeR d#eeR fd$d%ZT			d\d!eeeReeS f  d"eeR d#eeR fd&d'ZUd]d(eeR fd)d*ZVd+ed#eeR d,ee d-eeReRf fd.d/ZWd0d1d2eeeRd1f  d3ee* d-eed1 ee* f fd4d5ZXG d6d7 d7eYZZG d8d9 d9eZ[G d:d; d;Z\G d<d= d=e\Z]G d>d? d?e\Z^G d@dA dAe\Z_G dBdC dCeZ`	D	D	D	D	Ed^dFeadGeadHeadIeadJead-eRfdKdLZbebdEdEdEdEdEdMZce2 rd dNldmeZemfZfmgZgmhZh e.ebdEdEdEdEdOG dPdQ dQe`e-Zie/eijjei_jeijjjkdureijjjkjldRdSdTdUmdVdWeijj_kG dXdY dYeiZnG dZd[ d[ZodS )_    N)ABCabstractmethod)UserDict)contextmanager)abspathexists)TYPE_CHECKINGAnyDictListOptionalTupleUnion   )custom_object_save)PreTrainedFeatureExtractor)BaseImageProcessor)	ModelCard)
AutoConfigAutoTokenizer)ProcessorMixin)PreTrainedTokenizer)ModelOutputPushToHubMixinadd_end_docstrings	copy_funcinfer_frameworkis_tf_availableis_torch_availableis_torch_cuda_availableis_torch_hpu_availableis_torch_mlu_availableis_torch_mps_availableis_torch_musa_availableis_torch_npu_availableis_torch_xpu_availableloggingGenericTensorztorch.Tensorz	tf.Tensor)TFAutoModel)
DataLoaderDataset)PreTrainedModel)	AutoModel   )
KeyDataset)TFPreTrainedModelc                 C   s   t | dkr
td| d S )Nr-   z5This collate_fn is meant to be used with batch_size=1r   )len
ValueError)items r3   o/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/transformers/pipelines/base.pyno_collate_fnV   s   r5   c                    s  t | }t| d   tjrt| d   j}t |}|dkr,tj fdd| D ddS  dv r>tj fdd| D ddS |dkrT d	krTtj fd
d| D ddS t fdd| D }t fdd| D }| d   j}	|dkr||krtj fdd| D ddS tj	||f|	d| }
n(|dkrtj	|||d f|	d| }
n|dkrtj	|||d |d f|	d| }
t
| D ]\}}|dkr|dkr|  d  |
|t |  d  d f< q|  d  |
|d t |  d f< q|dkr1|dkr|  d  |
|t |  d  d d d f< q|  d  |
|d t |  d d d f< q|dkrq|dkrW|  d  |
|t |  d  d d d d d f< q|  d  |
|d t |  d d d d d f< q|
S  fdd| D S )Nr   r-   c                       g | ]}|  qS r3   r3   .0itemkeyr3   r4   
<listcomp>d       z_pad.<locals>.<listcomp>)dim)pixel_valuesimagec                    r6   r3   r3   r7   r:   r3   r4   r<   h   r=      input_featuresc                    r6   r3   r3   r7   r:   r3   r4   r<   k   r=   c                 3       | ]
}|  j d  V  qdS r-   Nshaper7   r:   r3   r4   	<genexpr>l       z_pad.<locals>.<genexpr>c                 3   rC   rD   rE   r7   r:   r3   r4   rG   m   rH   r   c                    r6   r3   r3   r7   r:   r3   r4   r<   t   r=   )dtype   leftc                    r6   r3   r3   r7   r:   r3   r4   r<      r=   )r0   
isinstancetorchTensorrF   catmaxminrI   zeros	enumerateclone)r2   r;   padding_valuepadding_side
batch_sizerF   r>   
max_length
min_lengthrI   tensorir9   r3   r:   r4   _pad\   sJ   ",*

20

84r^   c                    s   d }d }d u rd u rt dd ur#jd u rt djj}d ur3tdd  tdd }|d urI|d urI||krIt d| d| d|d urQ||d urW| fd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`.rW   rX   zAThe feature extractor, and tokenizer don't agree on padding side  != rightc                    s   t | d  }| D ]}t | |kr#tdt |  d| dq
i }|D ]4}|dv r<d u r9d ur9 }n}n|dv rC }n|dv rJd}n	|d	v rQd}nd}t| ||||< q(|S )
Nr   zEThe elements of the batch contain different keys. Cannot batch them (r_   )>   	input_ids>   input_valuesr?   rB   >   p_maskspecial_tokens_maskr-   >   attention_masktoken_type_ids)setkeysr1   r^   )r2   ri   r9   paddedr;   _padding_valuef_padding_valuefeature_extractorrX   t_padding_value	tokenizerr3   r4   inner   s0   zpad_collate_fn.<locals>.inner)r1   pad_token_idrX   getattr)rp   rn   t_padding_sidef_padding_siderq   r3   rl   r4   pad_collate_fn   s2   
rv   configmodel_classestask	frameworkc              
   K   s&  t  s
t s
tdt| tr||d< d}t o|dv }t  o#|dv }|r<|r1||dtf }|r<||dtf }|jrwg }	|jD ],}
t	
d}|r\t||
d	}|d	ur\|	| |rpt|d
|
 d	}|d	urp|	| qD|t|	 }t|dkrtd|  i }|D ]R}| }|dkr| drd|d< td n|dkr| drd|d< td z|j| fi |} t| dr|  } W  n ttfy   t ||j< Y qw t| trd}| D ]\}}|d| d| d7 }qtd|  d| d| d|d	u rt| 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_pipeliner3   >   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.eval zwhile loading with z, an error is thrown:

zCould not load model z$ with any of the following classes: z. See the original errors:

)r   r   RuntimeErrorrN   strgetr,   r(   architectures	importlibimport_modulers   appendtupler0   r1   copyendswithloggerwarningfrom_pretrainedhasattrr   OSError	traceback
format_exc__name__r2   r   	__class__)modelrw   rx   ry   rz   model_kwargsclass_tuplelook_ptlook_tfclassesarchitecturetransformers_module_classall_tracebackmodel_classkwargserror
class_nametracer3   r3   r4   infer_framework_load_model   s|   !






r   c                 K   sD   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.
    r|   )rx   r|   ry   rz   )rN   r   r   r   rw   r   )r   rx   ry   rz   r   rw   r3   r3   r4   infer_framework_from_model9  s   
r   revisionc                 C   s   t dt t st stdt| trKt r#t s#tj	| |d} n(t r1t s1t
j	| |d} nz	tj	| |d} W n tyJ   t
j	| |d} Y n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.r{   )r   )warningswarnFutureWarningr   r   r   rN   r   r,   r   r(   r   r   r   )r   r   rz   r3   r3   r4   get_framework`  s(   	

r   targeted_tasktask_optionsreturnc                 C   s   t  r	t s	d}nt rt  sd}| d }|r)||vr"td| || d }nd|v r4| d d }ntd|du r>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

        Tuple:
            - `str` The model string representing the default model for this pipeline.
            - `str` The revision of the model.
    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"N)r   r   r1   )r   rz   r   defaultsdefault_modelsr3   r3   r4   get_default_model_and_revision  s   r   r   r+   assistant_modelassistant_tokenizerc                    s     r|du r
dS tddksttstdt|tr;t|}t||d\}  j	j
jd t|}n| |}jj jjk}t fdd	d
D }|r]|r]d} |fS |du retd |fS )a  
    Prepares the assistant model and the assistant tokenizer for a pipeline whose model that can call `generate`.

    Args:
        model ([`PreTrainedModel`]):
            The main model that will be used by the pipeline to make predictions.
        assistant_model (`str` or [`PreTrainedModel`], *optional*):
            The assistant model that will be used by the pipeline to make predictions.
        assistant_tokenizer ([`PreTrainedTokenizer`], *optional*):
            The assistant tokenizer that will be used by the pipeline to encode data for the model.

    Returns:
        Tuple: The loaded assistant model and (optionally) the loaded tokenizer.
    N)NNrz   r}   zAssisted generation, triggered by the `assistant_model` argument, is only available for `PreTrainedModel` model instances. For instance, TF or JAX models are not supported.rw   )devicerI   c                 3   s(    | ]}t j|t  j|kV  qd S N)rs   rw   )r8   tokenloaded_assistant_modelr   r3   r4   rG     s
    
z'load_assistant_model.<locals>.<genexpr>)eos_token_idrr   bos_token_idzkThe assistant model has a different tokenizer than the main model. You should pass the assistant tokenizer.)can_generaters   rN   r+   r1   r   r   r   r   tor   rI   r   rw   
vocab_sizeall)r   r   r   assistant_config_loaded_assistant_tokenizersame_vocab_sizesame_special_tokensr3   r   r4   load_assistant_model  s2   

r   c                       s.   e Zd ZdZdededef fddZ  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.
    ry   r   reasonc                    s   t  | || _|| _d S r   )super__init__ry   r   )selfry   r   r   r   r3   r4   r     s   
zPipelineException.__init__)r   
__module____qualname____doc__r   r   __classcell__r3   r3   r   r4   r     s    "	r   c                   @   s   e Zd ZdZedd ZdS )ArgumentHandlerzQ
    Base interface for handling arguments for each [`~pipelines.Pipeline`].
    c                 O      t  r   NotImplementedError)r   argsr   r3   r3   r4   __call__     zArgumentHandler.__call__N)r   r   r   r   r   r   r3   r3   r3   r4   r     s    r   c                   @   s   e Zd ZdZg dZ	ddee dee dee defdd	Ze	d
d Z
e	deeee f fddZdeeee f defddZe	ddedee dee dee dd f
d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`): Where to save the outgoing data.
        input_path (`str`): Where to look for the input data.
        column (`str`): 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                 C   s   || _ || _|d ur|dndg| _t| jdk| _| jr'dd | jD | _|d ur<|s<tt| j r<t| j  d|d urOtt| jsQt| j dd S d S )N,r   r-   c                 S   s*   g | ]}d |v rt |d n||fqS )=)r   splitr8   cr3   r3   r4   r<   &  s   * z/PipelineDataFormat.__init__.<locals>.<listcomp>z already exists on diskz doesnt exist on disk)	r   r   r   r   r0   is_multi_columnsr   r   r   r   r   r   r   r   r3   r3   r4   r     s   zPipelineDataFormat.__init__c                 C   r   r   r   r   r3   r3   r4   __iter__0  r   zPipelineDataFormat.__iter__datac                 C   r   )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   r3   r3   r4   save4  s   zPipelineDataFormat.saver   c                 C   s`   t j| j\}}t jj|df}t|d}t|| W d   |S 1 s)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   r   binary_pathf_outputr3   r3   r4   save_binary>  s   

zPipelineDataFormat.save_binaryformatc                 C   sX   | dkrt ||||dS | dkrt||||dS | dkr$t||||d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   r3   r3   r4   from_strP  s   zPipelineDataFormat.from_strNF)r   r   r   r   SUPPORTED_FORMATSr   r   boolr   r   r   r   dictr   r   r   staticmethodr   r3   r3   r3   r4   r     s>    

	r   c                       sX   e Zd ZdZ	ddee dee dee f fddZdd	 Zd
ee	 fddZ
  ZS )r   aa  
    Support for pipelines using CSV data format.

    Args:
        output_path (`str`): Where to save the outgoing data.
        input_path (`str`): Where to look for the input data.
        column (`str`): The column to read.
        overwrite (`bool`, *optional*, defaults to `False`):
            Whether or not to overwrite the `output_path`.
    Fr   r   r   c                    s   t  j||||d d S )Nr   )r   r   r   r   r3   r4   r     s   zCsvPipelineDataFormat.__init__c                 #   sv    t | jd*}t|}|D ] | jr  fdd| jD V  q | jd  V  qW d    d S 1 s4w   Y  d S )Nrc                       i | ]	\}}| | qS r3   r3   r8   kr   rowr3   r4   
<dictcomp>      z2CsvPipelineDataFormat.__iter__.<locals>.<dictcomp>r   )r   r   r   
DictReaderr   r   )r   freaderr3   r
  r4   r     s   
"zCsvPipelineDataFormat.__iter__r   c                 C   sx   t | jd,}t|dkr*t|t|d  }|  || W d   dS W d   dS 1 s5w   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   r0   r   
DictWriterlistri   writeheader	writerows)r   r   r  writerr3   r3   r4   r     s   "zCsvPipelineDataFormat.saver  )r   r   r   r   r   r   r   r   r   r  r   r   r3   r3   r   r4   r   t  s    		r   c                       sT   e Zd ZdZ	ddee dee dee f fddZdd	 Zd
efddZ	  Z
S )r   ab  
    Support for pipelines using JSON file format.

    Args:
        output_path (`str`): Where to save the outgoing data.
        input_path (`str`): Where to look for the input data.
        column (`str`): The column to read.
        overwrite (`bool`, *optional*, defaults to `False`):
            Whether or not to overwrite the `output_path`.
    Fr   r   r   c                    sP   t  j||||d t|d}t|| _W d    d S 1 s!w   Y  d S )Nr   r  )r   r   r   r   load_entries)r   r   r   r   r   r  r   r3   r4   r     s   "zJsonPipelineDataFormat.__init__c                 #   s@    | j D ] | jr fdd| jD V  q | jd  V  qd S )Nc                    r  r3   r3   r  entryr3   r4   r    r  z3JsonPipelineDataFormat.__iter__.<locals>.<dictcomp>r   )r  r   r   r   r3   r  r4   r     s   
zJsonPipelineDataFormat.__iter__r   c                 C   s>   t | jd}t|| W d   dS 1 s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  r3   r3   r4   r     s   "zJsonPipelineDataFormat.saver  )r   r   r   r   r   r   r   r   r  r   r   r3   r3   r   r4   r     s    r   c                       sL   e Zd ZdZdd ZdefddZdeeee f de	f fdd	Z
  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`): Where to save the outgoing data.
        input_path (`str`): Where to look for the input data.
        column (`str`): The column to read.
        overwrite (`bool`, *optional*, defaults to `False`):
            Whether or not to overwrite the `output_path`.
    c                 c   sV    t jD ]$}d|v r%|d}| jrdd t| j|D V  qt|V  q|V  qd S )N	c                 S   s   i | ]	\\}}}||qS r3   r3   )r8   r   r   lr3   r3   r4   r    r  z4PipedPipelineDataFormat.__iter__.<locals>.<dictcomp>)sysstdinr   r   zipr   )r   liner3   r3   r4   r     s   

z PipedPipelineDataFormat.__iter__r   c                 C   s   t | dS )z^
        Print the data.

        Args:
            data (`dict`): The data to store.
        N)printr   r3   r3   r4   r     s   zPipedPipelineDataFormat.saver   c                    s   | j d u r	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   r3   r4   r     s
   
z#PipedPipelineDataFormat.save_binary)r   r   r   r   r   r  r   r   r   r   r   r   r3   r3   r   r4   r     s
    *	r   c                   @   s(   e Zd ZdZedd Zedd ZdS )_ScikitCompatzA
    Interface layer for the Scikit and Keras compatibility.
    c                 C   r   r   r   r   Xr3   r3   r4   	transform  r   z_ScikitCompat.transformc                 C   r   r   r   r#  r3   r3   r4   predict  r   z_ScikitCompat.predictN)r   r   r   r   r   r%  r&  r3   r3   r3   r4   r"    s    
r"  FThas_tokenizerhas_feature_extractorhas_image_processorhas_processorsupports_binary_outputc                 C   sL   d}| r|d7 }|r|d7 }|r|d7 }|r|d7 }|d7 }|r$|d7 }|S )Na  
    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.z
        tokenizer ([`PreTrainedTokenizer`]):
            The tokenizer that will be used by the pipeline to encode data for the model. This object inherits from
            [`PreTrainedTokenizer`].z
        feature_extractor ([`SequenceFeatureExtractor`]):
            The feature extractor that will be used by the pipeline to encode data for the model. This object inherits from
            [`SequenceFeatureExtractor`].z
        image_processor ([`BaseImageProcessor`]):
            The image processor that will be used by the pipeline to encode data for the model. This object inherits from
            [`BaseImageProcessor`].a4  
        processor ([`ProcessorMixin`]):
            The processor that will be used by the pipeline to encode data for the model. This object inherits from
            [`ProcessorMixin`]. Processor is a composite object that might contain `tokenizer`, `feature_extractor`, and
            `image_processor`.ak  
        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
        torch_dtype (`str` or `torch.dtype`, *optional*):
            Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model
            (`torch.float16`, `torch.bfloat16`, ... or `"auto"`)z
        binary_output (`bool`, *optional*, defaults to `False`):
            Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as
            the raw output data e.g. text.r3   )r'  r(  r)  r*  r+  	docstringr3   r3   r4   build_pipeline_init_args  s   r-  )r'  r(  r)  r*  r+  )PipelineChunkIteratorPipelineDatasetPipelineIteratorPipelinePackIterator)r'  r(  r)  r*  c                   @   s  e Zd ZdZdZdZdZdZdZ											dJde	d de
e 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dZ	dKde	eejf defddZdd Zdd Zede
d fd d!Zed"d# Zd$d% Zd&d' Zd(e	e e e!f fd)d*Z"e#d+d, Z$e#d-e%d.e&de&ee'f fd/d0Z(e#d1e&ee'f d2e&de)fd3d4Z*e#d5e)d6e&de%fd7d8Z+d9d: Z,d;d< Z-d=ed>efd?d@Z.dddAdBdCZ/dDdE Z0dFdG Z1dHdI Z2dS )L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.
    FTNr   r   )r+   r/   rp   rn   image_processor	processor	modelcardrz   ry   args_parserr   ztorch.devicetorch_dtypeztorch.dtypebinary_outputc                 K   s  |d u rt ||jd\}}|| _|| _|| _|| _|| _|| _|| _|| _	t
| jdd }|d ur8|
d ur8td|
d u rK|d urItt| }
nd}
t r| j	dkr|
dkrc| jjd urc| jj}
t|
tjr|
jdkrstdd	r{|
jd
krt st|
 d|
| _nt|
trd|
v rtdd	rd
|
v rt st|
 dt|
| _n{|
dk rtd| _npt rtd|
 | _nct rtd|
 | _nVt rtd|
 | _nIt rtd|
 | _n<t rtd|
 | _n/tdd	rtd|
 | _nt rtd|
 | _ntd| _n
|
d ur!|
nd| _tj r/| jj| _td| j  || _ | j	dkrb| jj| jkrbt| jt!rV| jdk sb|d u rb| j"| j t#| j|$dd |$dd \| _%| _&| j' rt(| jjdr| jjj)nd | _)t*+| jj,| _,| jjj-}|d ur||v r|.|}d|v r|$d| _)| j,j/di | | jd ur| jj0d ur| j,j0d u r| jj0| j,_0d| _1|$dd | _2|$dd | _3| j4di |\| _5| _6| _7| jd ur#t8| jd u | jd u | jd u gr#t
| jdd | _t
| jdd | _t
| jdd | _| jd u r<| jd ur>t| jt9r@| j| _d S d S d S d S )Nr   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}   rK   xpuT)check_devicehpuz6 is not available, you should use device="cpu" insteadcpuzmlu:zmusa:zcuda:znpu:zhpu:zxpu:zmps:zDevice set to use r   r   prefixrY   num_workersrp   rn   r3  r3   ):r   rw   ry   r   rp   rn   r3  r4  r5  rz   rs   r1   nextitervaluesr   r   rN   rO   typer%   r    r   r!   r#   r   r$   r"   distributedis_initializedr   r   r8  intr   r   popr   r   r   r   r>  r   deepcopygeneration_configtask_specific_paramsr   updaterr   
call_count_batch_size_num_workers_sanitize_parameters_preprocess_params_forward_params_postprocess_paramsr   r   )r   r   rp   rn   r3  r4  r5  rz   ry   r6  r   r7  r8  r   r9  rJ  this_task_paramsr3   r3   r4   r     s   



 


zPipeline.__init__save_directorysafe_serializationc                 K   s  | dd}|dur tdt |dddurtd||d< tj|r1t	
d| d dS tj|dd	 t| d
r| j }i }| D ]F\}}|d | jkrTqH| }|d j}	|	dd }
|
 d|d j |d< tdd |d D |d< tdd |d D |d< |||< qH|| jj_t| | ||d< | jj|fi | | jdur| jj|fi | | jdur| jj|fi | | jdur| jj|fi | | jdur| j| dS dS )a  
        Save the pipeline's model and tokenizer.

        Args:
            save_directory (`str` or `os.PathLike`):
                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.
            kwargs (`Dict[str, Any]`, *optional*):
                Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
        use_auth_tokenNzrThe `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.r   zV`token` and `use_auth_token` are both specified. Please set only the argument `token`.zProvided path (z#) should be a directory, not a fileT)exist_ok_registered_implimpl.rK   c                 s       | ]}|j V  qd S r   r   r   r3   r3   r4   rG   D      z+Pipeline.save_pretrained.<locals>.<genexpr>r}   c                 s   r[  r   r\  r   r3   r3   r4   rG   E  r]  r~   rU  )rG  r   r   r   r   r1   r   r   isfiler   r   makedirsr   rX  r   r2   r   r   r   r   r   r   rw   custom_pipelinesr   save_pretrainedrp   rn   r3  r5  )r   rT  rU  r   rV  pipeline_infor`  ry   infomodule_namelast_moduler3   r3   r4   ra    sR   









zPipeline.save_pretrainedc                 C      | |S zn
        Scikit / Keras interface to transformers' pipelines. This method will forward to __call__().
        r3   r#  r3   r3   r4   r%  [     zPipeline.transformc                 C   rf  rg  r3   r#  r3   r3   r4   r&  a  rh  zPipeline.predictr   c                 C   s   t | jddS )zU
        Torch dtype of the model (if it's Pytorch model), `None` otherwise.
        rI   N)rs   r   r   r3   r3   r4   r7  g  s   zPipeline.torch_dtypec                 c   sz   | j dkr,t| jdkrdnd| j  dV  W d   dS 1 s%w   Y  dS | jjdkrOtj| j dV  W d   dS 1 sHw   Y  dS | jjdkrrtj| j dV  W d   dS 1 skw   Y  dS | jjdkrtj| j dV  W d   dS 1 sw   Y  dS | jjd	krtj| j dV  W d   dS 1 sw   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~   rK   z/CPU:0z/device:GPU:Ncudamlumusar:  )	rz   r~   r   rC  rO   ri  rj  rk  r:  r   r3   r3   r4   device_placementn  s,   
""""""
zPipeline.device_placementc                 K   s   |  || 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   inputsr3   r3   r4   ensure_tensor_on_device  s   z Pipeline.ensure_tensor_on_devicec                    s   t |trt fdd| D S t |tr$ fdd| D S t |tr7t fdd| D S t |trF fdd|D S t |trWt fdd|D S t |tjrb|	 S |S )Nc                       i | ]\}}| | qS r3   rm  r8   namer\   r   r   r3   r4   r        z5Pipeline._ensure_tensor_on_device.<locals>.<dictcomp>c                    rp  r3   rq  rr  rt  r3   r4   r    ru  c                    rp  r3   rq  rr  rt  r3   r4   r    ru  c                       g | ]} | qS r3   rq  r7   rt  r3   r4   r<         z5Pipeline._ensure_tensor_on_device.<locals>.<listcomp>c                    rv  r3   rq  r7   rt  r3   r4   r<     rw  )
rN   r   r2   r  r   r  r   rO   rP   r   )r   rn  r   r3   rt  r4   rm    s   





z!Pipeline._ensure_tensor_on_devicesupported_modelsc              	   C   s   t |tsJg }| D ]\}}t |tr|t| q|| qt|drH|jj D ]\}}t |trA|dd |D  q-||j	 q-|}| j
jj	|vrft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                 S   s   g | ]}|j qS r3   r\  )r8   mr3   r3   r4   r<     s    z-Pipeline.check_model_type.<locals>.<listcomp>zThe model 'z' is not supported for z. Supported models are rZ  N)rN   r  r2   r   extendr   r   ry  _extra_contentr   r   r   r   r   ry   )r   rx  supported_models_namesr   
model_namer   r3   r3   r4   check_model_type  s&   



zPipeline.check_model_typec                 K      t d)aD  
        _sanitize_parameters will be called with any excessive named arguments from either `__init__` or `__call__`
        methods. It should return 3 dictionaries of the resolved parameters used by the various `preprocess`,
        `forward` and `postprocess` methods. Do not fill dictionaries if the caller didn't specify a kwargs. This
        lets 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_parametersr3   r3   r4   rO       zPipeline._sanitize_parametersinput_preprocess_parametersc                 K   r  )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  r3   r3   r4   
preprocess  s   zPipeline.preprocessinput_tensorsforward_parametersc                 K   r  )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  r3   r3   r4   _forward  r  zPipeline._forwardmodel_outputspostprocess_parametersc                 K   r  )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  r3   r3   r4   postprocess  s   zPipeline.postprocessc                 C   s   t jS r   )rO   no_gradr   r3   r3   r4   get_inference_context     zPipeline.get_inference_contextc              	   K   s   |   e | jdkrd|d< | j|fi |}nA| jdkrP|  }| # | j|| jd}| j|fi |}| j|tdd}W d    n1 sJw   Y  ntd| j dW d    |S W d    |S 1 slw   Y  |S )	Nr~   Ftrainingr}   )r   r=  z
Framework z is not supported)rl  rz   r  r  rm  r   rO   r1   )r   model_inputsforward_paramsr  inference_contextr3   r3   r4   forward  s*   




zPipeline.forwardr?  rY   c                 C   s   t |tjjrt|| j|}n|dkrtd d}t|| j|}dt	j
vr0td dt	j
d< | jd ur8| jn| j}|dkrAtnt| j|}	t||||	d}
t|
| j||d}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r?  rY   
collate_fnloader_batch_size)rN   collectionsabcSizedr/  r  r   r   r0  r   environrc  rn   r3  r5   rv   rp   r)   r  r  r   rn  r?  rY   preprocess_paramsr  postprocess_paramsdatasetrn   r  
dataloadermodel_iteratorfinal_iteratorr3   r3   r4   get_iterator  s"   


zPipeline.get_iterator)r?  rY   c             
   O   s  |r
t d|  |d u r| jd u rd}n| j}|d u r(| jd u r%d}n| j}| jdi |\}}}i | j|}i | j|}i | j|}|  jd7  _| jdkrd| j	dkrd| j
jdkrdt d td uolt|t}	t|tj}
t|t}|	p}|
p}|}| j	dko|	p|
p|}|r|r| ||||||}t|}|S | ||||S |r| ||||||S |r| ||||S | j	dkrt| trtt| |g|||||S | ||||S )	NzIgnoring args : r   r-   
   r}   ri  zlYou seem to be using the pipelines sequentially on GPU. In order to maximize efficiency please use a datasetr3   )r   r   rN  rM  rO  rP  rQ  rR  rL  rz   r   rC  warning_oncer*   rN   typesGeneratorTyper  r  	run_multiiterateChunkPipeliner@  rA  
run_single)r   rn  r?  rY   r   r   r  r  r  
is_datasetis_generatoris_listis_iterablecan_use_iteratorr  outputsr3   r3   r4   r   %  s^   

 
zPipeline.__call__c                    s    fdd|D S )Nc                    s   g | ]
} | qS r3   r  r7   r  r  r  r   r3   r4   r<   f  s    z&Pipeline.run_multi.<locals>.<listcomp>r3   )r   rn  r  r  r  r3   r  r4   r  e  s   zPipeline.run_multic                 C   s:   | j |fi |}| j|fi |}| j|fi |}|S r   )r  r  r  )r   rn  r  r  r  r  r  r  r3   r3   r4   r  h  s   zPipeline.run_singlec                 c   s"    |D ]}|  ||||V  qd S r   r  )r   rn  r  r  r  r  r3   r3   r4   r  n  s   zPipeline.iterate)NNNNNNr   NNNF)T)3r   r   r   r   _load_processor_load_image_processor_load_feature_extractor_load_tokenizerdefault_input_namesr   r   r   r   r   r   r   r   r   rF  r  r   r   PathLikera  r%  r&  propertyr7  r   rl  ro  rm  r   r  r  r   rO  r	   r
   r'   r  r   r  r  r  r  r  r   r  r  r  r3   r3   r3   r4   r2  ^  s    	


 
G
#
  
@r2  r   pipelinezpipeline file)objectobject_classobject_filesz.from_pretrainedr   c                   @   s&   e Zd Zdd ZdedefddZdS )r  c           	      C   sN   g }| j |fi |D ]}| j|fi |}|| q| j|fi |}|S r   )r  r  r   r  )	r   rn  r  r  r  all_outputsr  r  r  r3   r3   r4   r  }  s   zChunkPipeline.run_singler?  rY   c                 C   s   dt jvrtd dt jd< |dkrtd d}t|| j|}| jd ur)| jn| j}|dkr2t	nt
| j|}	t||||	d}
t|
| j||d}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   rc  r   r.  r  rn   r3  r5   rv   rp   r)   r1  r  r0  r  r  r3   r3   r4   r    s   


zChunkPipeline.get_iteratorN)r   r   r   r  rF  r  r3   r3   r3   r4   r  |  s    r  c                   @   s   e Zd Zdeeef deeef ddfddZdee fddZd	ede	eeef fd
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dZdd ZdS )PipelineRegistrysupported_taskstask_aliasesr   Nc                 C   s   || _ || _d S r   )r  r  )r   r  r  r3   r3   r4   r     s   
zPipelineRegistry.__init__c                 C   s(   t | j t | j  }|  |S r   )r  r  ri   r  sort)r   supported_taskr3   r3   r4   get_supported_tasks  s   z$PipelineRegistry.get_supported_tasksry   c                 C   s   || j v r
| j | }|| jv r| j| }||d fS |drO|d}t|dkrG|d dkrG|d dkrG| jd }d}|||d |d ffS td	| d
td| d|  dg  )Ntranslationr   rA   r   r   r   r-   rJ   zInvalid translation task z#, use 'translation_XX_to_YY' formatzUnknown task z, available tasks are translation_XX_to_YY)r  r  
startswithr   r0   r   r  )r   ry   r   tokensr3   r3   r4   
check_task  s   






$
zPipelineRegistry.check_taskpipeline_classpt_modeltf_modelr   rC  c                 C   s   || j v rt| d| d |d u rd}nt|ts|f}|d u r&d}nt|ts.|f}|||d}|d urLd|vrHd|v sDd|v rHd|i}||d< |d urT||d	< || j |< ||i|_d S )
Nz6 is already registered. Overwriting pipeline for task z...r3   )rY  r}   r~   r   r}   r~   r   rC  )r  r   r   rN   r   rX  )r   ry   r  r  r  r   rC  	task_implr3   r3   r4   register_pipeline  s&   
	


z"PipelineRegistry.register_pipelinec                 C   s   | j S r   )r  r   r3   r3   r4   to_dict  r  zPipelineRegistry.to_dict)NNNN)r   r   r   r
   r   r	   r   r   r  r   r  rC  r   r   r  r  r3   r3   r3   r4   r    s0    &
#r  )NNNr   )FFFFT)pr  r   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   r5  r   models.autor   r   processing_utilsr   tokenization_utilsr   utilsr   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   
tensorflowr~   models.auto.modeling_tf_autor(   rO   torch.utils.datar)   r*   modeling_utilsr+   models.auto.modeling_autor,   pt_utilsr.   modeling_tf_utilsr/   
get_loggerr   r   r5   r^   rv   r   rC  r   r   r   r   r   	Exceptionr   r   r   r   r   r   r"  r  r-  PIPELINE_INIT_ARGStransformers.pipelines.pt_utilsr.  r/  r0  r1  r2  push_to_hubr   r   replacer  r  r3   r3   r3   r4   <module>   s  $D
5B
k
'"

.
8
q,*0
D	     