Ë
    T^(hÔ0  ã                   óÈ   — 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
j                  e«      Z G d„ d	e«      Z e	 ed
¬«      «       G d„ de«      «       Zy)é    N)ÚListÚUnioné   )ÚTruncationStrategy)Úadd_end_docstringsÚloggingé   )ÚArgumentHandlerÚChunkPipelineÚbuild_pipeline_init_argsc                   ó   — e Zd ZdZd„ Zd„ Zy)Ú%ZeroShotClassificationArgumentHandlerz‰
    Handles arguments for zero-shot for text classification by turning each possible label into an NLI
    premise/hypothesis pair.
    c                 óª   — t        |t        «      r=|j                  d«      D �cg c]#  }|j                  «       sŒ|j                  «       ‘Œ% }}|S c c}w )Nú,)Ú
isinstanceÚstrÚsplitÚstrip)ÚselfÚlabelsÚlabels      úm/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/pipelines/zero_shot_classification.pyÚ_parse_labelsz3ZeroShotClassificationArgumentHandler._parse_labels   sA   € Ü�fœcÔ"Ø17·±¸cÓ1BÖT¨ÀeÇkÁkÅm�e—k‘k•mÐTˆFÐTØˆùò Us
   ¤AºAc           
      ó\  — t        |«      dk(  st        |«      dk(  rt        d«      ‚|j                  |d   «      |k(  rt        dj                  |«      «      ‚t        |t        «      r|g}g }|D ]2  }|j                  |D �cg c]  }||j                  |«      g‘Œ c}«       Œ4 ||fS c c}w )Nr   z>You must include at least one label and at least one sequence.z»The 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.)ÚlenÚ
ValueErrorÚformatr   r   Úextend)r   Ú	sequencesr   Úhypothesis_templateÚsequence_pairsÚsequencer   s          r   Ú__call__z.ZeroShotClassificationArgumentHandler.__call__   sÃ   € Üˆv‹;˜!Òœs 9›~°Ò2ÜÐ]Ó^Ð^Ø×%Ñ% f¨Q¡iÓ0Ð4GÒGÜðwç‘&Ð,Ó-ó	ð ô �i¤Ô%Ø"˜ˆIàˆØ!ò 	gˆHØ×!Ñ!Ð^dÖ"eÐUZ HÐ.A×.HÑ.HÈÓ.OÒ#PÒ"eÕfð	gð ˜yÐ(Ð(ùò #fs   ÂB)
N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r#   © ó    r   r   r      s   „ ñò
ó
)r)   r   T)Úhas_tokenizerc                   óž   ‡ — e 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e   f   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).
    c                 ó|   •— || _         t        ‰| �  |i |¤Ž | j                  dk(  rt        j                  d«       y y )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.)Ú_args_parserÚsuperÚ__init__Úentailment_idÚloggerÚwarning)r   Úargs_parserÚargsÚkwargsÚ	__class__s       €r   r1   z'ZeroShotClassificationPipeline.__init__W   sB   ø€ Ø'ˆÔÜ‰Ñ˜$Ð) &Ò)Ø×Ñ Ò#Ü�N‰Nðkõð $r)   c                 ó¶   — | j                   j                  j                  j                  «       D ](  \  }}|j	                  «       j                  d«      sŒ&|c S  y)NÚentailr.   )ÚmodelÚconfigÚlabel2idÚitemsÚlowerÚ
startswith)r   r   Úinds      r   r2   z,ZeroShotClassificationPipeline.entailment_id`   sL   € àŸ*™*×+Ñ+×4Ñ4×:Ñ:Ó<ò 	‰JˆE�3Ø�{‰{‹}×'Ñ'¨Õ1Ø’
ð	ð r)   Tc                 ó‚  — | j                   }| j                  j                  €:t        j	                  d«       | j                  j
                  | j                  _        	 | j                  |||||¬«      }|S # t        $ r?}dt        |«      v r%| j                  ||||t        j                  ¬«      }n|‚Y d}~|S d}~ww xY 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_tokenr3   ÚerrorÚ	eos_tokenÚ	Exceptionr   r   ÚDO_NOT_TRUNCATE)	r   r!   rE   rC   rF   r7   rD   ÚinputsÚes	            r   Ú_parse_and_tokenizez2ZeroShotClassificationPipeline._parse_and_tokenizeg   sÏ   € ð Ÿ™ˆØ�>‰>×#Ñ#Ð+ä�L‰Lð)ôð (,§~¡~×'?Ñ'?ˆD�N‰NÔ$ð	Ø—^‘^ØØ#5Ø-ØØ%ð $ó ˆFð2 ˆøô% ò 	Øœc !›fÑ$ð Ÿ™Ø"Ø'9Ø#1Ø#Ü1×AÑAð (ó ‘ð �ó ð ˆûð%	ús   ÁA6 Á6	B>Á?4B9Â9B>c                 óì   — |j                  dd «      �|d   |d<   t        j                  d«       i }d|v r!| j                  j	                  |d   «      |d<   d|v r|d   |d<   i }d|v r|d   |d<   |i |fS )NÚmulti_classÚmulti_labelz�The `multi_class` argument has been deprecated and renamed to `multi_label`. `multi_class` will be removed in a future version of Transformers.Úcandidate_labelsr    )Úgetr3   r4   r/   r   )r   r7   Úpreprocess_paramsÚpostprocess_paramss       r   Ú_sanitize_parametersz3ZeroShotClassificationPipeline._sanitize_parameters‘   s®   € Ø�:‰:�m TÓ*Ð6Ø$*¨=Ñ$9ˆF�=Ñ!Ü�N‰NðUôð ÐØ Ñ'Ø48×4EÑ4E×4SÑ4SÐTZÐ[mÑTnÓ4oÐÐ0Ñ1Ø  FÑ*Ø7=Ð>SÑ7TÐÐ3Ñ4àÐØ˜FÑ"Ø06°}Ñ0EÐ˜}Ñ-Ø  "Ð&8Ð8Ð8r)   r   c                 ó”   •— t        |«      dk(  rn)t        |«      dk(  rd|vr	|d   |d<   nt        d|› �«      ‚t        ‰| �  |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	   rT   z%Unable to understand extra arguments )r   r   r0   r#   )r   r   r6   r7   r8   s       €r   r#   z'ZeroShotClassificationPipeline.__call__£   s^   ø€ ôH ˆt‹9˜Š>ØÜ�‹Y˜!Š^Ð 2¸&Ñ @Ø)-¨a©ˆFÐ%Ò&äÐDÀTÀFÐKÓLÐLä‰wÑ 	Ñ4¨VÑ4Ð4r)   c              #   óÔ   K  — | j                  |||«      \  }}t        t        ||«      «      D ]6  \  }\  }}| j                  |g«      }	||d   |t	        |«      dz
  k(  dœ|	¥–— Œ8 y ­w)Nr   r	   ©Úcandidate_labelr"   Úis_last)r/   Ú	enumerateÚziprP   r   )
r   rN   rT   r    r!   r   Úir\   Úsequence_pairÚmodel_inputs
             r   Ú
preprocessz)ZeroShotClassificationPipeline.preprocessÐ   s�   è ø€ Ø$(×$5Ñ$5°fÐ>NÐPcÓ$dÑ!ˆ˜	ä3<¼SÐAQÐSaÓ=bÓ3cò 	Ñ/ˆAÑ/� Ø×2Ñ2°M°?ÓCˆKð $3Ø% a™LØ¤Ð$4Ó 5¸Ñ 9Ñ9ñð ð	ó ñ	ùs   ‚A&A(c                 óŠ  — |d   }|d   }| j                   j                  D �ci c]  }|||   “Œ
 }}| j                  dk(  r| j                  j                  n| j                  j
                  }dt        j                  |«      j                  j                  «       v rd|d<    | j                  di |¤Ž}|||d   dœ|¥}|S c c}w )	Nr\   r"   ÚptÚ	use_cacheFr]   r[   r(   )
rH   Úmodel_input_namesrG   r;   ÚforwardÚcallÚinspectÚ	signatureÚ
parametersÚkeys)	r   rN   r\   r"   ÚkÚmodel_inputsÚmodel_forwardÚoutputsÚmodel_outputss	            r   Ú_forwardz'ZeroShotClassificationPipeline._forwardÝ   sÎ   € Ø Ð!2Ñ3ˆØ˜*Ñ%ˆØ.2¯n©n×.NÑ.NÖO¨˜˜6 !™9™ÐOˆÐOà.2¯n©nÀÒ.D˜Ÿ
™
×*Ò*È$Ï*É*Ï/É/ˆØœ'×+Ñ+¨MÓ:×EÑE×JÑJÓLÑLØ(-ˆL˜Ñ%Ø�$—*‘*Ñ,˜|Ñ,ˆð  /Ø Ø˜iÑ(ñ
ð ð	
ˆð Ðùò Ps   £C c                 ó  — |D �cg c]  }|d   ‘Œ	 }}|D �cg c]  }|d   ‘Œ	 }}| j                   dk(  rCt        j                  |D �cg c]#  }|d   j                  «       j	                  «       ‘Œ% c}«      }n4t        j                  |D �cg c]  }|d   j	                  «       ‘Œ c}«      }|j
                  d   }t        |«      }	||	z  }
|j                  |
|	df«      }|st        |«      dk(  r`| j                  }|dk(  rdnd}|d||gf   }t        j                  |«      t        j                  |«      j                  dd	¬
«      z  }|d   }nM|d| j                  f   }t        j                  |«      t        j                  |«      j                  dd	¬
«      z  }t        t        |d   j                  «       «      «      }|d   |D �cg c]  }||   ‘Œ	 c}|d|f   j                  «       dœS c c}w c c}w c c}w c c}w c c}w )Nr\   r"   re   Úlogitsr   r.   r	   .T)Úkeepdims).r	   )r"   r   Úscores)rG   ÚnpÚconcatenateÚfloatÚnumpyÚshaper   Úreshaper2   ÚexpÚsumÚlistÚreversedÚargsortÚtolist)r   rr   rS   rq   rT   r   Úoutputru   ÚNÚnÚnum_sequencesÚreshaped_outputsr2   Úcontradiction_idÚentail_contr_logitsrw   Úentail_logitsÚtop_indsr`   s                      r   Úpostprocessz*ZeroShotClassificationPipeline.postprocessï   sö  € ØFSÖT¸7˜GÐ$5Ó6ÐTÐÐTØ8EÖF¨W�W˜ZÓ(ÐFˆ	ÐFØ�>‰>˜TÒ!Ü—^‘^ÐTaÖ$bÈ& V¨HÑ%5×%;Ñ%;Ó%=×%CÑ%CÕ%EÒ$bÓc‰Fä—^‘^ÈMÖ$ZÀ& V¨HÑ%5×%;Ñ%;Õ%=Ò$ZÓ[ˆFØ�L‰L˜‰OˆÜÐ Ó!ˆØ˜Q™ˆØ!Ÿ>™>¨=¸!¸RÐ*@ÓAÐáœ#Ð.Ó/°1Ò4à ×.Ñ.ˆMØ%2°aÒ%7™r¸QÐØ"2°3Ð9IÈ=Ð8YÐ3YÑ"ZÐÜ—V‘VÐ/Ó0´2·6±6Ð:MÓ3N×3RÑ3RÐSUÐ`dÐ3RÓ3eÑeˆFØ˜F‘^‰Fð -¨S°$×2DÑ2DÐ-DÑEˆMÜ—V‘V˜MÓ*¬R¯V©V°MÓ-B×-FÑ-FÀrÐTXÐ-FÓ-YÑYˆFäœ ¨¡×!2Ñ!2Ó!4Ó5Ó6ˆà! !™Ø4<Ö=¨qÐ'¨Ó*Ò=Ø˜Q ˜[Ñ)×0Ñ0Ó2ñ
ð 	
ùò1 UùÚFùâ$bùâ$Zùò* >s   …G-—G2Á(G7Â
G<ÇH)NzThis example is {}.)F)r$   r%   r&   r'   r   r1   Úpropertyr2   r   Ú
ONLY_FIRSTrP   rX   r   r   r   r#   rc   rs   r�   Ú__classcell__)r8   s   @r   r,   r,   .   sp   ø„ ñ%ñN $IÓ#Jõ ð ñó ðð '+¸tÐPb×PmÑPmó(òT9ð$+5à˜˜d 3™i˜Ñ(õ+5óZò÷$
r)   r,   )rj   Útypingr   r   r{   rx   Útokenization_utilsr   Úutilsr   r   Úbaser
   r   r   Ú
get_loggerr$   r3   r   r,   r(   r)   r   ú<module>r–      se   ðÛ ß ã å 3ß /ß JÑ Jð 
ˆ×	Ñ	˜HÓ	%€ô)¨Oô )ñ@ Ñ,¸4Ô@ÓAô]
 ]ó ]
ó Bñ]
r)   