o
    Zh0                     @   s   d dl Z d dlmZmZ d dlZddlmZ ddlm	Z	m
Z
 ddlmZmZmZ e
eZG dd	 d	eZe	ed
dG dd deZdS )    N)ListUnion   )TruncationStrategy)add_end_docstringslogging   )ArgumentHandlerChunkPipelinebuild_pipeline_init_argsc                   @   s    e Zd ZdZdd Zdd ZdS )%ZeroShotClassificationArgumentHandlerz
    Handles arguments for zero-shot for text classification by turning each possible label into an NLI
    premise/hypothesis pair.
    c                 C   s"   t |trdd |dD }|S )Nc                 S   s   g | ]
}|  r|  qS  )strip.0labelr   r   ^/var/www/auris/lib/python3.10/site-packages/transformers/pipelines/zero_shot_classification.py
<listcomp>       zGZeroShotClassificationArgumentHandler._parse_labels.<locals>.<listcomp>,)
isinstancestrsplit)selflabelsr   r   r   _parse_labels   s   
z3ZeroShotClassificationArgumentHandler._parse_labelsc                    s   t |dkst |dkrtd |d  kr td t|tr(|g}g }|D ]| fdd|D  q,||fS )Nr   z>You must include at least one label and at least one sequence.zThe provided hypothesis_template "{}" was not able to be formatted with the target labels. Make sure the passed template includes formatting syntax such as {{}} where the label should go.c                    s   g | ]	}  |gqS r   )formatr   hypothesis_templatesequencer   r   r   )   s    zBZeroShotClassificationArgumentHandler.__call__.<locals>.<listcomp>)len
ValueErrorr   r   r   extend)r   	sequencesr   r   sequence_pairsr   r   r   __call__   s   
z.ZeroShotClassificationArgumentHandler.__call__N)__name__
__module____qualname____doc__r   r%   r   r   r   r   r      s    r   T)Zhas_tokenizerc                       s   e Zd ZdZe f fdd	Zedd Zddej	fddZ
d	d
 Zdeeee f f fddZdddZdd ZdddZ  ZS )ZeroShotClassificationPipelinea  
    NLI-based zero-shot classification pipeline using a `ModelForSequenceClassification` trained on NLI (natural
    language inference) tasks. Equivalent of `text-classification` pipelines, but these models don't require a
    hardcoded number of potential classes, they can be chosen at runtime. It usually means it's slower but it is
    **much** more flexible.

    Any combination of sequences and labels can be passed and each combination will be posed as a premise/hypothesis
    pair and passed to the pretrained model. Then, the logit for *entailment* is taken as the logit for the candidate
    label being valid. Any NLI model can be used, but the id of the *entailment* label must be included in the model
    config's :attr:*~transformers.PretrainedConfig.label2id*.

    Example:

    ```python
    >>> from transformers import pipeline

    >>> oracle = pipeline(model="facebook/bart-large-mnli")
    >>> oracle(
    ...     "I have a problem with my iphone that needs to be resolved asap!!",
    ...     candidate_labels=["urgent", "not urgent", "phone", "tablet", "computer"],
    ... )
    {'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['urgent', 'phone', 'computer', 'not urgent', 'tablet'], 'scores': [0.504, 0.479, 0.013, 0.003, 0.002]}

    >>> oracle(
    ...     "I have a problem with my iphone that needs to be resolved asap!!",
    ...     candidate_labels=["english", "german"],
    ... )
    {'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['english', 'german'], 'scores': [0.814, 0.186]}
    ```

    Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)

    This NLI pipeline can currently be loaded from [`pipeline`] using the following task identifier:
    `"zero-shot-classification"`.

    The models that this pipeline can use are models that have been fine-tuned on an NLI task. See the up-to-date list
    of available models on [huggingface.co/models](https://huggingface.co/models?search=nli).
    c                    s4   || _ t j|i | | jdkrtd d S d S )NzFailed to determine 'entailment' label id from the label2id mapping in the model config. Setting to -1. Define a descriptive label2id mapping in the model config to ensure correct outputs.)_args_parsersuper__init__entailment_idloggerwarning)r   Zargs_parserargskwargs	__class__r   r   r.   W   s   
z'ZeroShotClassificationPipeline.__init__c                 C   s2   | j jj D ]\}}| dr|  S qdS )NZentailr+   )modelconfigZlabel2iditemslower
startswith)r   r   indr   r   r   r/   `   s
   z,ZeroShotClassificationPipeline.entailment_idTc           	   
   K   s   | j }| jjdu rtd | jj| j_z| j|||||d}W |S  tyH } zdt|v r;| j||||tj	d}n|W Y d}~|S d}~ww )ze
        Parse arguments and tokenize only_first so that hypothesis (label) is not truncated
        NzfTokenizer was not supporting padding necessary for zero-shot, attempting to use  `pad_token=eos_token`)add_special_tokensreturn_tensorspadding
truncationz	too short)
	framework	tokenizerZ	pad_tokenr0   errorZ	eos_token	Exceptionr   r   ZDO_NOT_TRUNCATE)	r   r$   r>   r<   r?   r3   r=   inputser   r   r   _parse_and_tokenizeg   s:   

z2ZeroShotClassificationPipeline._parse_and_tokenizec                 K   s|   | dd d ur|d |d< td i }d|v r#| j|d |d< d|v r-|d |d< i }d|v r9|d |d< |i |fS )NZmulti_classmulti_labelzThe `multi_class` argument has been deprecated and renamed to `multi_label`. `multi_class` will be removed in a future version of Transformers.candidate_labelsr   )getr0   r1   r,   r   )r   r3   Zpreprocess_paramsZpostprocess_paramsr   r   r   _sanitize_parameters   s   
z3ZeroShotClassificationPipeline._sanitize_parametersr#   c                    sR   t |dkrnt |dkrd|vr|d |d< ntd| t j|fi |S )a  
        Classify the sequence(s) given as inputs. See the [`ZeroShotClassificationPipeline`] documentation for more
        information.

        Args:
            sequences (`str` or `List[str]`):
                The sequence(s) to classify, will be truncated if the model input is too large.
            candidate_labels (`str` or `List[str]`):
                The set of possible class labels to classify each sequence into. Can be a single label, a string of
                comma-separated labels, or a list of labels.
            hypothesis_template (`str`, *optional*, defaults to `"This example is {}."`):
                The template used to turn each label into an NLI-style hypothesis. This template must include a {} or
                similar syntax for the candidate label to be inserted into the template. For example, the default
                template is `"This example is {}."` With the candidate label `"sports"`, this would be fed into the
                model like `"<cls> sequence to classify <sep> This example is sports . <sep>"`. The default template
                works well in many cases, but it may be worthwhile to experiment with different templates depending on
                the task setting.
            multi_label (`bool`, *optional*, defaults to `False`):
                Whether or not multiple candidate labels can be true. If `False`, the scores are normalized such that
                the sum of the label likelihoods for each sequence is 1. If `True`, the labels are considered
                independent and probabilities are normalized for each candidate by doing a softmax of the entailment
                score vs. the contradiction score.

        Return:
            A `dict` or a list of `dict`: Each result comes as a dictionary with the following keys:

            - **sequence** (`str`) -- The sequence for which this is the output.
            - **labels** (`List[str]`) -- The labels sorted by order of likelihood.
            - **scores** (`List[float]`) -- The probabilities for each of the labels.
        r   r   rH   z%Unable to understand extra arguments )r    r!   r-   r%   )r   r#   r2   r3   r4   r   r   r%      s   $z'ZeroShotClassificationPipeline.__call__NThis example is {}.c           
      c   sb    |  |||\}}tt||D ]\}\}}| |g}	||d |t|d kd|	V  qd S )Nr   r   candidate_labelr   is_last)r,   	enumerateziprF   r    )
r   rD   rH   r   r$   r#   irM   Zsequence_pairZmodel_inputr   r   r   
preprocess   s   z)ZeroShotClassificationPipeline.preprocessc                    s    d } d } fdd| j jD }| jdkr| jjn| jj}dt|j	 v r.d|d< | jd
i |}|| d d	|}|S )NrM   r   c                    s   i | ]}| | qS r   r   )r   krD   r   r   
<dictcomp>   s    z;ZeroShotClassificationPipeline._forward.<locals>.<dictcomp>ptZ	use_cacheFrN   rL   r   )
rA   Zmodel_input_namesr@   r6   forwardcallinspect	signature
parameterskeys)r   rD   rM   r   Zmodel_inputsZmodel_forwardoutputsmodel_outputsr   rT   r   _forward   s   z'ZeroShotClassificationPipeline._forwardFc                    sB  dd |D  dd |D }| j dkrtdd |D }n
tdd |D }|jd }t }|| }|||df}|sEt d	krl| j}	|	dkrNdnd}
|d
|
|	gf }t|t|jddd }|d }n|d
| jf }t|t|jddd }t	t
|d  }|d  fdd|D |d|f  dS )Nc                 S      g | ]}|d  qS )rM   r   r   r]   r   r   r   r          z>ZeroShotClassificationPipeline.postprocess.<locals>.<listcomp>c                 S   r`   )r   r   ra   r   r   r   r      rb   rV   c                 S   s   g | ]
}|d     qS logits)floatnumpyr   outputr   r   r   r      r   c                 S   s   g | ]}|d    qS rc   )rf   rg   r   r   r   r      s    r   r+   r   .T)Zkeepdims).r   c                    s   g | ]} | qS r   r   )r   rQ   rH   r   r   r   
  rb   )r   r   scores)r@   npZconcatenateshaper    Zreshaper/   expsumlistreversedZargsorttolist)r   r^   rG   r#   rd   NnZnum_sequencesZreshaped_outputsr/   Zcontradiction_idZentail_contr_logitsrj   Zentail_logitsZtop_indsr   ri   r   postprocess   s,   


z*ZeroShotClassificationPipeline.postprocess)NrK   )F)r&   r'   r(   r)   r   r.   propertyr/   r   Z
ONLY_FIRSTrF   rJ   r   r   r   r%   rR   r_   rt   __classcell__r   r   r4   r   r*   .   s    '	

*
-r*   )rY   typingr   r   rf   rk   Ztokenization_utilsr   utilsr   r   baser	   r
   r   Z
get_loggerr&   r0   r   r*   r   r   r   r   <module>   s    
 