o
    h0                     @   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G d
d deZdS )    N)ListUnion   )TruncationStrategy)add_end_docstringslogging   )PIPELINE_INIT_ARGSArgumentHandlerChunkPipelinec                   @   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   e/var/www/html/ai/venv/lib/python3.10/site-packages/transformers/pipelines/zero_shot_classification.py
<listcomp>   s    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   c                       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   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 )Nentailr*   )modelconfig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	tokenizer	pad_tokenr/   error	eos_token	Exceptionr   r   DO_NOT_TRUNCATE)	r   r#   r@   r>   rA   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 )N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   )getr/   r0   r+   r   )r   r3   preprocess_params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   rN   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ziprK   r   )
r   rI   rN   r   r#   r"   irU   sequence_pair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 )NrU   r   c                    s   i | ]}| | qS r   r   )r   krI   r   r   
<dictcomp>   s    z;ZeroShotClassificationPipeline._forward.<locals>.<dictcomp>pt	use_cacheFrV   rT   r   )
rC   model_input_namesrB   r7   forwardcallinspect	signature
parameterskeys)r   rI   rU   r   model_inputsmodel_forwardoutputsmodel_outputsr   r^   r   _forward   s   z'ZeroShotClassificationPipeline._forwardFc                    s"  dd |D  dd |D }t dd |D }|jd }t }|| }|||df}|s5t dkr\| j}	|	dkr>d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 )rU   r   r   rk   r   r   r   r          z>ZeroShotClassificationPipeline.postprocess.<locals>.<listcomp>c                 S   rn   )r   r   ro   r   r   r   r      rp   c                 S   s   g | ]}|d    qS )logits)numpy)r   outputr   r   r   r      s    r   r*   r   .T)keepdims).r   c                    s   g | ]} | qS r   r   )r   rY   rN   r   r   r     rp   )r   r   scores)npconcatenateshaper   reshaper.   expsumlistreversedargsorttolist)r   rl   rM   r"   rq   Nnnum_sequencesreshaped_outputsr.   contradiction_identail_contr_logitsrv   entail_logitstop_indsr   ru   r   postprocess   s(   

z*ZeroShotClassificationPipeline.postprocess)NrS   )F)r%   r&   r'   r(   r   r-   propertyr.   r   
ONLY_FIRSTrK   rR   r   r   r   r$   r\   rm   r   __classcell__r   r   r4   r   r)   .   s    '	

*
-r)   )re   typingr   r   rr   rw   tokenization_utilsr   utilsr   r   baser	   r
   r   
get_loggerr%   r/   r   r)   r   r   r   r   <module>   s    
 