§
    ‚ŠtjÈ.  ã                   óÔ   — d dl 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j        e¦  «        Z G d„ de	¦  «        Z e ed	¬
¦  «        ¦  «         G d„ de
¦  «        ¦   «         ZdS )é    Né   )ÚTruncationStrategy)Úadd_end_docstringsÚloggingé   )ÚArgumentHandlerÚChunkPipelineÚbuild_pipeline_init_argsc                   ó   — e Zd ZdZd„ Z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                 ón   — t          |t          ¦  «        rd„ |                     d¦  «        D ¦   «         }|S )Nc                 ó^   — g | ]*}|                      ¦   «         ¯|                      ¦   «         ‘Œ+S © )Ústrip)Ú.0Úlabels     úm/var/www/html/CA-Chatbot/venv/lib/python3.11/site-packages/transformers/pipelines/zero_shot_classification.pyú
<listcomp>zGZeroShotClassificationArgumentHandler._parse_labels.<locals>.<listcomp>   s-   € ÐTÐTÐT¨ÀeÇkÂkÁmÄmÐT�e—k’k‘m”mÐTÐTÐTó    ú,)Ú
isinstanceÚstrÚsplit)ÚselfÚlabelss     r   Ú_parse_labelsz3ZeroShotClassificationArgumentHandler._parse_labels   s9   € Ý�f�cÑ"Ô"ð 	UØTÐT°·²¸cÑ1BÔ1BÐTÑTÔTˆFØˆr   c                 ó^  ‡‡— t          |¦  «        dk    st          |¦  «        dk    rt          d¦  «        ‚‰                     |d         ¦  «        ‰k    rt          d‰› d�¦  «        ‚t          |t          ¦  «        r|g}g }|D ]$Š|                     ˆˆfd„|D ¦   «         ¦  «         Œ%||fS )Nr   z>You must include at least one label and at least one sequence.z"The provided hypothesis_template "z•" 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                 ó>   •— g | ]}‰‰                      |¦  «        g‘ŒS r   )Úformat)r   r   Úhypothesis_templateÚsequences     €€r   r   zBZeroShotClassificationArgumentHandler.__call__.<locals>.<listcomp>&   s.   ø€ Ð"eÐ"eÐ"eÐUZ HÐ.A×.HÒ.HÈÑ.OÔ.OÐ#PÐ"eÐ"eÐ"er   )ÚlenÚ
ValueErrorr   r   r   Úextend)r   Ú	sequencesr   r    Úsequence_pairsr!   s      ` @r   Ú__call__z.ZeroShotClassificationArgumentHandler.__call__   së   øø€ Ýˆv‰;Œ;˜!ÒÐ�s 9™~œ~°Ò2Ð2ÝÐ]Ñ^Ô^Ð^Ø×%Ò% f¨Q¤iÑ0Ô0Ð4GÒGÐGÝðqÐ5Hð qð qð qñô ð õ
 �i¥Ñ%Ô%ð 	$Ø"˜ˆIàˆØ!ð 	gð 	gˆHØ×!Ò!Ð"eÐ"eÐ"eÐ"eÐ"eÐ^dÐ"eÑ"eÔ"eÑfÔfÐfÐfà˜yÐ(Ð(r   N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r'   r   r   r   r   r      s<   € € € € € ðð ð
ð ð ð
)ð )ð )ð )ð )r   r   T)Úhas_tokenizerc                   ó²   ‡ — e Zd ZdZdZdZdZdZ e¦   «         fˆ fd„	Z	e
d„ ¦   «         Zddej        fd„Zd„ Zdeee         z  fˆ fd	„Zdd„Zd„ Zdd„Zˆ x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).
    FTc                 ó–   •— || _          t          ¦   «         j        di |¤Ž | j        dk    rt                               d¦  «         d S d S )Néÿÿÿÿz¼Failed 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.r   )Ú_args_parserÚsuperÚ__init__Úentailment_idÚloggerÚwarning)r   Úargs_parserÚkwargsÚ	__class__s      €r   r3   z'ZeroShotClassificationPipeline.__init__Y   sd   ø€ Ø'ˆÔØ�‰ŒÔÐ"Ð"˜6Ð"Ð"Ð"ØÔ Ò#Ð#Ý�NŠNðkñô ð ð ð ð $Ð#r   c                 ó®   — | j         j        j                             ¦   «         D ]0\  }}|                     ¦   «                              d¦  «        r|c S Œ1dS )NÚentailr0   )ÚmodelÚconfigÚlabel2idÚitemsÚlowerÚ
startswith)r   r   Úinds      r   r4   z,ZeroShotClassificationPipeline.entailment_idb   sZ   € àœ*Ô+Ô4×:Ò:Ñ<Ô<ð 	ð 	‰JˆE�3Ø�{Š{‰}Œ}×'Ò'¨Ñ1Ô1ð Ø�
�
�
ðàˆrr   c                 óX  — d}| j         j        €0t                               d¦  «         | j         j        | j         _        	 |                       |||||¬¦  «        }nO# t
          $ rB}dt          |¦  «        v r%|                       ||||t          j        ¬¦  «        }n|‚Y d}~nd}~ww xY w|S )ze
        Parse arguments and tokenize only_first so that hypothesis (label) is not truncated
        ÚptNzfTokenizer was not supporting padding necessary for zero-shot, attempting to use  `pad_token=eos_token`)Úadd_special_tokensÚreturn_tensorsÚpaddingÚ
truncationz	too short)	Ú	tokenizerÚ	pad_tokenr5   ÚerrorÚ	eos_tokenÚ	Exceptionr   r   ÚDO_NOT_TRUNCATE)	r   r&   rG   rE   rH   r8   rF   ÚinputsÚes	            r   Ú_parse_and_tokenizez2ZeroShotClassificationPipeline._parse_and_tokenizei   sé   € ð ˆØŒ>Ô#Ð+å�LŠLð)ñô ð ð (,¤~Ô'?ˆDŒNÔ$ð	Ø—^’^ØØ#5Ø-ØØ%ð $ñ ô ˆFˆFøõ ð 	ð 	ð 	Ø�c !™fœfÐ$Ð$ð ŸšØ"Ø'9Ø#1Ø#Ý1ÔAð (ñ ô ��ð �ð ����øøøøð	øøøð$ ˆs   Á A Á
B'Á%8B"Â"B'c                 óž   — i }d|v r#| j                              |d         ¦  «        |d<   d|v r|d         |d<   i }d|v r|d         |d<   |i |fS )NÚcandidate_labelsr    Úmulti_label)r1   r   )r   r8   Úpreprocess_paramsÚpostprocess_paramss       r   Ú_sanitize_parametersz3ZeroShotClassificationPipeline._sanitize_parameters“   sƒ   € ØÐØ Ð'Ð'Ø48Ô4E×4SÒ4SÐTZÐ[mÔTnÑ4oÔ4oÐÐ0Ñ1Ø  FÐ*Ð*Ø7=Ð>SÔ7TÐÐ3Ñ4àÐØ˜FÐ"Ð"Ø06°}Ô0EÐ˜}Ñ-Ø  "Ð&8Ð8Ð8r   r%   c                 óÊ   •— t          |¦  «        dk    rn5t          |¦  «        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   rS   z%Unable to understand extra arguments )r"   r#   r2   r'   )r   r%   Úargsr8   r9   s       €r   r'   z'ZeroShotClassificationPipeline.__call__Ÿ   sz   ø€ õH ˆt‰9Œ9˜Š>ˆ>ØÝ�‰YŒY˜!Š^ˆ^Ð 2¸&Ð @Ð @Ø)-¨a¬ˆFÐ%Ñ&Ð&åÐKÀTÐKÐKÑLÔLÐLà�u‰wŒwÔ 	Ð4Ð4¨VÐ4Ð4Ð4r   NúThis example is {}.c              #   óþ   K  — |                       |||¦  «        \  }}t          t          ||¦  «        ¦  «        D ]B\  }\  }}|                      |g¦  «        }	||d         |t	          |¦  «        dz
  k    dœ|	¥V — ŒCd S )Nr   r   ©Úcandidate_labelr!   Úis_last)r1   Ú	enumerateÚziprQ   r"   )
r   rO   rS   r    r&   r%   Úir]   Úsequence_pairÚmodel_inputs
             r   Ú
preprocessz)ZeroShotClassificationPipeline.preprocessÌ   sº   è è € Ø$(×$5Ò$5°fÐ>NÐPcÑ$dÔ$dÑ!ˆ˜	å3<½SÐAQÐSaÑ=bÔ=bÑ3cÔ3cð 	ð 	Ñ/ˆAÑ/� Ø×2Ò2°M°?ÑCÔCˆKð $3Ø% aœLØ¥Ð$4Ñ 5Ô 5¸Ñ 9Ò9ðð ð ð	ð ð ð ð ð	ð 	r   c                 óæ   ‡— ‰d         }‰d         }ˆfd„| j         j        D ¦   «         }| j        j        }dt	          j        |¦  «        j        v rd|d<    | j        di |¤Ž}||‰d         dœ|¥}|S )	Nr]   r!   c                 ó"   •— i | ]}|‰|         “ŒS r   r   )r   ÚkrO   s     €r   ú
<dictcomp>z;ZeroShotClassificationPipeline._forward.<locals>.<dictcomp>Ü   s   ø€ ÐOÐOÐO¨˜˜6 !œ9ÐOÐOÐOr   Ú	use_cacheFr^   r\   r   )rI   Úmodel_input_namesr<   ÚforwardÚinspectÚ	signatureÚ
parameters)r   rO   r]   r!   Úmodel_inputsÚmodel_forwardÚoutputsÚmodel_outputss    `      r   Ú_forwardz'ZeroShotClassificationPipeline._forwardÙ   s¨   ø€ Ø Ð!2Ô3ˆØ˜*Ô%ˆØOÐOÐOÐO¨d¬nÔ.NÐOÑOÔOˆàœ
Ô*ˆØ�'Ô+¨MÑ:Ô:ÔEÐEÐEØ(-ˆL˜Ñ%Ø�$”*Ð,Ð,˜|Ð,Ð,ˆð  /Ø Ø˜iÔ(ð
ð 
ð ð	
ˆð Ðr   c                 ó:  ‡— d„ |D ¦   «         Šd„ |D ¦   «         }t          j        d„ |D ¦   «         ¦  «        }|j        d         }t          ‰¦  «        }||z  }|                     ||df¦  «        }|st          ‰¦  «        dk    rd| j        }	|	dk    rdnd}
|d|
|	gf         }t          j        |¦  «        t          j        |¦  «                             dd¬	¦  «        z  }|d
         }nM|d| j        f         }t          j        |¦  «        t          j        |¦  «                             dd¬	¦  «        z  }t          t          |d          
                    ¦   «         ¦  «        ¦  «        }|d         ˆfd„|D ¦   «         |d|f                              ¦   «         dœS )Nc                 ó   — g | ]
}|d          ‘ŒS )r]   r   ©r   rq   s     r   r   z>ZeroShotClassificationPipeline.postprocess.<locals>.<listcomp>ì   s   € ÐTÐTÐT¸7˜GÐ$5Ô6ÐTÐTÐTr   c                 ó   — g | ]
}|d          ‘ŒS )r!   r   rv   s     r   r   z>ZeroShotClassificationPipeline.postprocess.<locals>.<listcomp>í   s   € ÐFÐFÐF¨W�W˜ZÔ(ÐFÐFÐFr   c                 óf   — g | ].}|d                                ¦   «                              ¦   «         ‘Œ/S )Úlogits)ÚfloatÚnumpy)r   Úoutputs     r   r   z>ZeroShotClassificationPipeline.postprocess.<locals>.<listcomp>î   s5   € Ð ^Ð ^Ð ^Àf ¨Ô!1×!7Ò!7Ñ!9Ô!9×!?Ò!?Ñ!AÔ!AÐ ^Ð ^Ð ^r   r   r0   r   .T)Úkeepdims).r   c                 ó    •— g | ]
}‰|         ‘ŒS r   r   )r   ra   rS   s     €r   r   z>ZeroShotClassificationPipeline.postprocess.<locals>.<listcomp>  s   ø€ Ð=Ð=Ð=¨qÐ'¨Ô*Ð=Ð=Ð=r   )r!   r   Úscores)ÚnpÚconcatenateÚshaper"   Úreshaper4   ÚexpÚsumÚlistÚreversedÚargsortÚtolist)r   rr   rT   r%   ry   ÚNÚnÚnum_sequencesÚreshaped_outputsr4   Úcontradiction_idÚentail_contr_logitsr   Úentail_logitsÚtop_indsrS   s                  @r   Úpostprocessz*ZeroShotClassificationPipeline.postprocessë   sÂ  ø€ ØTÐTÀmÐTÑTÔTÐØFÐF¸ÐFÑFÔFˆ	Ý”Ð ^Ð ^ÐP]Ð ^Ñ ^Ô ^Ñ_Ô_ˆØŒL˜ŒOˆÝÐ Ñ!Ô!ˆØ˜Q™ˆØ!Ÿ>š>¨=¸!¸RÐ*@ÑAÔAÐàð 
	Z�#Ð.Ñ/Ô/°1Ò4Ð4à Ô.ˆMØ%2°aÒ%7Ð%7˜r˜r¸QÐØ"2°3Ð9IÈ=Ð8YÐ3YÔ"ZÐÝ”VÐ/Ñ0Ô0µ2´6Ð:MÑ3NÔ3N×3RÒ3RÐSUÐ`dÐ3RÑ3eÔ3eÑeˆFØ˜F”^ˆFˆFð -¨S°$Ô2DÐ-DÔEˆMÝ”V˜MÑ*Ô*­R¬V°MÑ-BÔ-B×-FÒ-FÀrÐTXÐ-FÑ-YÔ-YÑYˆFå� ¨¤×!2Ò!2Ñ!4Ô!4Ñ5Ô5Ñ6Ô6ˆà! !œØ=Ð=Ð=Ð=°HÐ=Ñ=Ô=Ø˜Q ˜[Ô)×0Ò0Ñ2Ô2ð
ð 
ð 	
r   )NrZ   )F)r(   r)   r*   r+   Ú_load_processorÚ_load_image_processorÚ_load_feature_extractorÚ_load_tokenizerr   r3   Úpropertyr4   r   Ú
ONLY_FIRSTrQ   rW   r   r†   r'   rd   rs   r’   Ú__classcell__)r9   s   @r   r.   r.   +   s  ø€ € € € € ð%ð %ðN €OØ!ÐØ#ÐØ€Oà#HÐ#HÑ#JÔ#Jð ð ð ð ð ð ð ðð ñ „Xðð '+¸tÐPbÔPmð(ð (ð (ð (ðT
9ð 
9ð 
9ð+5à˜˜cœ‘?ð+5ð +5ð +5ð +5ð +5ð +5ðZð ð ð ðð ð ð$
ð 
ð 
ð 
ð 
ð 
ð 
ð 
r   r.   )rl   r{   r€   Útokenization_pythonr   Úutilsr   r   Úbaser   r	   r
   Ú
get_loggerr(   r5   r   r.   r   r   r   ú<module>rž      s  ðØ €€€à Ð Ð Ð à 4Ð 4Ð 4Ð 4Ð 4Ð 4Ø /Ð /Ð /Ð /Ð /Ð /Ð /Ð /Ø JÐ JÐ JÐ JÐ JÐ JÐ JÐ JÐ JÐ Jð 
ˆÔ	˜HÑ	%Ô	%€ð)ð )ð )ð )ð )¨Oñ )ô )ð )ð< ÐÐ,Ð,¸4Ð@Ñ@Ô@ÑAÔAðY
ð Y
ð Y
ð Y
ð Y
 ]ñ Y
ô Y
ñ BÔAðY
ð Y
ð Y
r   