Ë
    ÜÓ^jÈ.  ã                   ó¸   — 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y)é    Né   )Ú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      úz/var/www/ramen.bs-engineer-server.com/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           
      óF  — t        |«      dk(  st        |«      dk(  rt        d«      ‚|j                  |d   «      |k(  rt        d|› d�«      ‚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 "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.)Ú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ÜØ4Ð5HÐ4Ið Jqð qóð ô
 �i¤Ô%Ø"˜ˆIàˆØ!ò 	gˆHØ×!Ñ!Ð^dÖ"eÐUZ HÐ.A×.HÑ.HÈÓ.OÒ#PÒ"eÕfð	gð ˜yÐ(Ð(ùò #fs   Á7B
N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__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        ‰| �  d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.r&   )Ú_args_parserÚsuperÚ__init__Úentailment_idÚloggerÚwarning)r   Úargs_parserÚkwargsÚ	__class__s      €r   r/   z'ZeroShotClassificationPipeline.__init__Y   s@   ø€ Ø'ˆÔÜ‰ÑÑ"˜6Ò"Ø×Ñ Ò#Ü�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   r0   z,ZeroShotClassificationPipeline.entailment_idb   sL   € àŸ*™*×+Ñ+×4Ñ4×:Ñ:Ó<ò 	‰JˆE�3Ø�{‰{‹}×'Ñ'¨Õ1Ø’
ð	ð r'   c                 ón  — d}| 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
        Ú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_tokenr1   ÚerrorÚ	eos_tokenÚ	Exceptionr   r   ÚDO_NOT_TRUNCATE)	r   r   rC   rA   rD   r4   rB   ÚinputsÚes	            r   Ú_parse_and_tokenizez2ZeroShotClassificationPipeline._parse_and_tokenizei   sË   € ð ˆØ�>‰>×#Ñ#Ð+ä�L‰Lð)ôð (,§~¡~×'?Ñ'?ˆD�N‰NÔ$ð	Ø—^‘^ØØ#5Ø-ØØ%ð $ó ˆFð2 ˆøô% ò 	Øœc !›fÑ$ð Ÿ™Ø"Ø'9Ø#1Ø#Ü1×AÑAð (ó ‘ð �ó ð ˆûð%	ús   ÁA, Á,	B4Á54B/Â/B4c                 óŽ   — i }d|v r!| j                   j                  |d   «      |d<   d|v r|d   |d<   i }d|v r|d   |d<   |i |fS )NÚcandidate_labelsr   Úmulti_label)r-   r   )r   r4   Úpreprocess_paramsÚpostprocess_paramss       r   Ú_sanitize_parametersz3ZeroShotClassificationPipeline._sanitize_parameters“   sz   € ØÐØ Ñ'Ø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   rO   z%Unable to understand extra arguments )r   r   r.   r!   )r   r   Úargsr4   r5   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ÚziprM   r   )
r   rK   rO   r   r   r   ÚirX   Ú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                  j                  }dt	        j
                  |«      j                  v rd|d<    | j                  di |¤Ž}|||d   dœ|¥}|S c c}w )NrX   r    Ú	use_cacheFrY   rW   r&   )rE   Úmodel_input_namesr8   ÚforwardÚinspectÚ	signatureÚ
parameters)	r   rK   rX   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àŸ
™
×*Ñ*ˆØœ'×+Ñ+¨MÓ:×EÑEÑEØ(-ˆL˜Ñ%Ø�$—*‘*Ñ,˜|Ñ,ˆð  /Ø Ø˜iÑ(ñ
ð ð	
ˆð Ðùò Ps   £Bc                 óz  — |D �cg c]  }|d   ‘Œ	 }}|D �cg c]  }|d   ‘Œ	 }}t        j                  |D �cg c]#  }|d   j                  «       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 )NrX   r    Úlogitsr   r,   r   .T)Úkeepdims).r   )r    r   Úscores)ÚnpÚconcatenateÚfloatÚnumpyÚshaper   Úreshaper0   ÚexpÚsumÚlistÚreversedÚargsortÚtolist)r   rk   rP   rj   rO   r   Úoutputrn   ÚNÚnÚnum_sequencesÚreshaped_outputsr0   Úcontradiction_idÚentail_contr_logitsrp   Ú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Ü—‘ÐP]Ö ^Àf ¨Ñ!1×!7Ñ!7Ó!9×!?Ñ!?Õ!AÒ ^Ó_ˆØ�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ñ
ð 	
ùò+ UùÚFùÚ ^ùò* >s   …F)—F.¸(F3ÆF8)NzThis example is {}.)F)r"   r#   r$   r%   Ú_load_processorÚ_load_image_processorÚ_load_feature_extractorÚ_load_tokenizerr   r/   Úpropertyr0   r   Ú
ONLY_FIRSTrM   rS   r   ry   r!   r_   rl   r†   Ú__classcell__)r5   s   @r   r*   r*   +   s€   ø„ ñ%ðN €OØ!ÐØ#ÐØ€Oá#HÓ#Jõ ð ñó ðð '+¸tÐPb×PmÑPmó(òT
9ð+5à˜˜c™‘?õ+5óZò÷$
r'   r*   )rd   rt   rq   Útokenization_pythonr   Úutilsr   r   Úbaser   r	   r
   Ú
get_loggerr"   r1   r   r*   r&   r'   r   ú<module>r’      sa   ðÛ ã å 4ß /ß JÑ Jð 
ˆ×	Ñ	˜HÓ	%€ô)¨Oô )ñ< Ñ,¸4Ô@ÓAôY
 ]ó Y
ó BñY
r'   