U
    9%e(                     @   s   d dl Z d dlZd dlmZ d dlZddlmZmZm	Z	m
Z
 ddlmZmZmZ e	 rbddlmZ e
 rtddlmZ d	d
 Zdd ZG dd deZeedG dd deZdS )    N)Dict   )ExplicitEnumadd_end_docstringsis_tf_availableis_torch_available   )PIPELINE_INIT_ARGSGenericTensorPipeline)2TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES)/MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMESc                 C   s   ddt |    S )Ng      ?)npexp)_outputs r   i/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/transformers/pipelines/text_classification.pysigmoid   s    r   c                 C   s0   t j| ddd}t | | }||jddd S )NT)ZaxisZkeepdims)r   maxr   sum)r   ZmaxesZshifted_expr   r   r   softmax   s    r   c                   @   s   e Zd ZdZdZdZdS )ClassificationFunctionr   r   noneN)__name__
__module____qualname__SIGMOIDSOFTMAXNONEr   r   r   r   r      s   r   a   
        return_all_scores (`bool`, *optional*, defaults to `False`):
            Whether to return all prediction scores or just the one of the predicted class.
        function_to_apply (`str`, *optional*, defaults to `"default"`):
            The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:

            - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model
              has several labels, will apply the softmax function on the output.
            - `"sigmoid"`: Applies the sigmoid function on the output.
            - `"softmax"`: Applies the softmax function on the output.
            - `"none"`: Does not apply any function on the output.
    c                       sh   e Zd ZdZdZejZ fddZdddZ	 fd	d
Z
eeef dddZdd ZdddZ  ZS )TextClassificationPipelinea=  
    Text classification pipeline using any `ModelForSequenceClassification`. See the [sequence classification
    examples](../task_summary#sequence-classification) for more information.

    Example:

    ```python
    >>> from transformers import pipeline

    >>> classifier = pipeline(model="distilbert-base-uncased-finetuned-sst-2-english")
    >>> classifier("This movie is disgustingly good !")
    [{'label': 'POSITIVE', 'score': 1.0}]

    >>> classifier("Director tried too much.")
    [{'label': 'NEGATIVE', 'score': 0.996}]
    ```

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

    This text classification pipeline can currently be loaded from [`pipeline`] using the following task identifier:
    `"sentiment-analysis"` (for classifying sequences according to positive or negative sentiments).

    If multiple classification labels are available (`model.config.num_labels >= 2`), the pipeline will run a softmax
    over the results. If there is a single label, the pipeline will run a sigmoid over the result.

    The models that this pipeline can use are models that have been fine-tuned on a sequence classification task. See
    the up-to-date list of available models on
    [huggingface.co/models](https://huggingface.co/models?filter=text-classification).
    Fc                    s*   t  jf | | | jdkr tnt d S )Ntf)super__init__Zcheck_model_type	frameworkr   r   )selfkwargs	__class__r   r   r#   S   s    z#TextClassificationPipeline.__init__N c                 K   s   |}i }t | jjdr(|d kr(| jjj}t|ts:|d krL||d< d|d< n*|d k	rvtdt |rnd |d< nd|d< t|t	rt
|  }|d k	r||d< |i |fS )Nreturn_all_scorestop_kF_legacyz`return_all_scores` is now deprecated,  if want a similar functionality use `top_k=None` instead of `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.r   function_to_apply)hasattrmodelconfigr*   
isinstanceintwarningswarnUserWarningstrr   upper)r%   r*   r-   r+   tokenizer_kwargsZpreprocess_paramsZpostprocess_paramsr   r   r   _sanitize_parameters\   s(    



z/TextClassificationPipeline._sanitize_parametersc                    s6   t  j||}d|k}t|d tr.|r.|gS |S dS )aD  
        Classify the text(s) given as inputs.

        Args:
            args (`str` or `List[str]` or `Dict[str]`, or `List[Dict[str]]`):
                One or several texts to classify. In order to use text pairs for your classification, you can send a
                dictionary containing `{"text", "text_pair"}` keys, or a list of those.
            top_k (`int`, *optional*, defaults to `1`):
                How many results to return.
            function_to_apply (`str`, *optional*, defaults to `"default"`):
                The function to apply to the model outputs in order to retrieve the scores. Accepts four different
                values:

                If this argument is not specified, then it will apply the following functions according to the number
                of labels:

                - If the model has a single label, will apply the sigmoid function on the output.
                - If the model has several labels, will apply the softmax function on the output.

                Possible values are:

                - `"sigmoid"`: Applies the sigmoid function on the output.
                - `"softmax"`: Applies the softmax function on the output.
                - `"none"`: Does not apply any function on the output.

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

            - **label** (`str`) -- The label predicted.
            - **score** (`float`) -- The corresponding probability.

            If `top_k` is used, one such dictionary is returned per label.
        r+   r   N)r"   __call__r1   r6   )r%   argsr&   resultr,   r'   r   r   r:   z   s
    "z#TextClassificationPipeline.__call__)returnc                 K   s   | j }t|tr&| jf |d|i|S t|trt|dkrt|d trt|d dkr| jf |d d |d d |d|S t|trtd| j|fd|i|S )Nreturn_tensorsr   r   r   )textZ	text_pairr>   zThe pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.)r$   r1   dictZ	tokenizerlistlen
ValueError)r%   inputsr8   r>   r   r   r   
preprocess   s     
4
 
 
z%TextClassificationPipeline.preprocessc                 C   sB   | j dkr| jjn| jj}dt|j kr6d|d< | jf |S )NptZ	use_cacheF)r$   r/   forwardcallinspect	signature
parameterskeys)r%   Zmodel_inputsZmodel_forwardr   r   r   _forward   s    z#TextClassificationPipeline._forwardr   Tc                    sN  |d krx j jjdks$ j jjdkr,tj}nL j jjdksH j jjdkrPtj}n(t j jdrr|d krr j jj}ntj	}|d d }|
 }|tjkrt|}n2|tjkrt|}n|tj	kr|}ntd| |dkr|r j jj|   |  dS  fd	d
t|D }|sJ|jdd dd |d k	rJ|d | }|S )NZmulti_label_classificationr   Zsingle_label_classificationr-   Zlogitsr   z+Unrecognized `function_to_apply` argument: labelscorec                    s(   g | ] \}} j jj| | d qS )rN   )r/   r0   id2labelitem).0irP   r%   r   r   
<listcomp>   s    z:TextClassificationPipeline.postprocess.<locals>.<listcomp>c                 S   s   | d S )NrP   r   )xr   r   r   <lambda>       z8TextClassificationPipeline.postprocess.<locals>.<lambda>T)keyreverse)r/   r0   Zproblem_typeZ
num_labelsr   r   r   r.   r-   r   numpyr   r   rC   rQ   ZargmaxrR   r   	enumeratesort)r%   Zmodel_outputsr-   r+   r,   outputsZscoresZdict_scoresr   rU   r   postprocess   s6    




$

z&TextClassificationPipeline.postprocess)NNr)   )Nr   T)r   r   r   __doc__r*   r   r   r-   r#   r9   r:   r   r6   r
   rE   rM   r`   __classcell__r   r   r'   r   r    "   s   	
+r    )rI   r3   typingr   r\   r   utilsr   r   r   r   baser	   r
   r   Zmodels.auto.modeling_tf_autor   Zmodels.auto.modeling_autor   r   r   r   r    r   r   r   r   <module>   s"   