Ë
    îÍ:jÐI  ã                   óœ  — d dl Z d dlZd dlmZmZ ddlmZ ddlmZ ddl	m
Z
mZmZmZ ddlmZmZ  e«       r
d dlZdd	lmZ  e«       rdd
lmZ  ej.                  e«      Z G d„ de j4                  «      Z e
 ed¬«      «       G d„ de«      «       Z e
 ed¬«      «       G d„ de«      «       Z e
 ed¬«      «       G d„ de«      «       Zy)é    N)ÚAnyÚUnioné   )ÚGenerationConfig)ÚTruncationStrategy)Úadd_end_docstringsÚis_tf_availableÚis_torch_availableÚloggingé   )ÚPipelineÚbuild_pipeline_init_args)Ú/TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES)Ú,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMESc                   ó   — e Zd ZdZdZy)Ú
ReturnTyper   r   N)Ú__name__Ú
__module__Ú__qualname__ÚTENSORSÚTEXT© ó    ú€/home/mcse/projects/srt_converter/srt-converter-venv/lib/python3.12/site-packages/transformers/pipelines/text2text_generation.pyr   r      s   „ Ø€GØ�Dr   r   T)Úhas_tokenizerc            	       óø   ‡ — e Zd ZdZdZdZdZdZdZ e	dd¬«      Z
dZˆ fd„Z	 	 	 	 	 	 dd	„Zd
ededefd„Zd„ Zdeeee   f   dedeeeef      fˆ fd„Zej0                  fd„Zd„ Zej8                  dfd„Zˆ xZS )ÚText2TextGenerationPipelinea9  
    Pipeline for text to text generation using seq2seq models.

    Unless the model you're using explicitly sets these generation parameters in its configuration files
    (`generation_config.json`), the following default values will be used:
    - max_new_tokens: 256
    - num_beams: 4

    Example:

    ```python
    >>> from transformers import pipeline

    >>> generator = pipeline(model="mrm8488/t5-base-finetuned-question-generation-ap")
    >>> generator(
    ...     "answer: Manuel context: Manuel has created RuPERTa-base with the support of HF-Transformers and Google"
    ... )
    [{'generated_text': 'question: Who created the RuPERTa-base?'}]
    ```

    Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial). You can pass text
    generation parameters to this pipeline to control stopping criteria, decoding strategy, and more. Learn more about
    text generation parameters in [Text generation strategies](../generation_strategies) and [Text
    generation](text_generation).

    This Text2TextGenerationPipeline pipeline can currently be loaded from [`pipeline`] using the following task
    identifier: `"text2text-generation"`.

    The models that this pipeline can use are models that have been fine-tuned on a translation task. See the
    up-to-date list of available models on
    [huggingface.co/models](https://huggingface.co/models?filter=text2text-generation). For a list of available
    parameters, see the [following
    documentation](https://huggingface.co/docs/transformers/en/main_classes/text_generation#transformers.generation.GenerationMixin.generate)

    Usage:

    ```python
    text2text_generator = pipeline("text2text-generation")
    text2text_generator("question: What is 42 ? context: 42 is the answer to life, the universe and everything")
    ```TFé   é   )Úmax_new_tokensÚ	num_beamsÚ	generatedc                 ó‚   •— t        ‰| �  |i |¤Ž | j                  | j                  dk(  rt        «       y t
        «       y )NÚtf)ÚsuperÚ__init__Úcheck_model_typeÚ	frameworkr   r   ©ÚselfÚargsÚkwargsÚ	__class__s      €r   r&   z$Text2TextGenerationPipeline.__init__T   s>   ø€ Ü‰Ñ˜$Ð) &Ò)à×Ñà�~‰~ Ò%ô <õ	
ô >õ	
r   c                 ó¬  — i }|�||d<   |}	i }
|�$|€"|rt         j                  nt         j                  }|�||
d<   |�||
d<   |�H| j                  j	                  |d¬«      }t        |«      dkD  rt        j                  d«       |d   |d	<   | j                  �| j                  |	d
<   | j                  �| j                  |	d<   | j                  |	d<   ||	|
fS )NÚ
truncationÚreturn_typeÚclean_up_tokenization_spacesF)Úadd_special_tokensr   z©Stopping on a multiple token sequence is not yet supported on transformers. The first token of the stop sequence will be used as the stop sequence string in the interim.r   Úeos_token_idÚassistant_modelÚ	tokenizerÚassistant_tokenizer)
r   r   r   r5   ÚencodeÚlenÚwarningsÚwarnr4   r6   )r*   Úreturn_tensorsÚreturn_textr0   r1   r/   Ústop_sequenceÚgenerate_kwargsÚpreprocess_paramsÚforward_paramsÚpostprocess_paramsÚstop_sequence_idss               r   Ú_sanitize_parametersz0Text2TextGenerationPipeline._sanitize_parameters]   s  € ð ÐØÐ!Ø.8Ð˜lÑ+à(ˆàÐØÐ%¨+Ð*=Ù0>œ*×,Ò,ÄJÇOÁOˆKØÐ"Ø0;Ð˜}Ñ-à'Ð3ØA]ÐÐ=Ñ>àÐ$Ø $§¡× 5Ñ 5°mÐX]Ð 5Ó ^ÐÜÐ$Ó%¨Ò)Ü—‘ðbôð /@ÀÑ.BˆO˜NÑ+à×ÑÐ+Ø04×0DÑ0DˆNÐ,Ñ-Ø×#Ñ#Ð/Ø*.¯.©.ˆN˜;Ñ'Ø48×4LÑ4LˆNÐ0Ñ1à  .Ð2DÐDÐDr   Úinput_lengthÚ
min_lengthÚ
max_lengthc                  ó   — y)új
        Checks whether there might be something wrong with given input with regard to the model.
        Tr   ©r*   rD   rE   rF   s       r   Úcheck_inputsz(Text2TextGenerationPipeline.check_inputs‡   s   € ð r   c                óŒ  — | j                   �| j                   nd}t        |d   t        «      r;| j                  j                  €t        d«      ‚|d   D �cg c]  }||z   ‘Œ	 c}f}d}n1t        |d   t        «      r||d   z   f}d}nt        d|d   › d�«      ‚ | j                  |||| j                  dœŽ}d	|v r|d	= |S c c}w )
NÚ r   zOPlease make sure that the tokenizer has a pad_token_id when using a batch inputTFz `args[0]`: zI have the wrong format. The should be either of type `str` or type `list`)Úpaddingr/   r;   Útoken_type_ids)	ÚprefixÚ
isinstanceÚlistr5   Úpad_token_idÚ
ValueErrorÚstrÚ	TypeErrorr(   )r*   r/   r+   rO   ÚargrM   Úinputss          r   Ú_parse_and_tokenizez/Text2TextGenerationPipeline._parse_and_tokenize�   sÜ   € Ø $§¡Ð 7�—’¸RˆÜ�d˜1‘gœtÔ$Ø�~‰~×*Ñ*Ð2Ü Ð!rÓsÐsØ-1°!©WÖ5 c�V˜c“\Ò5Ð7ˆDØ‰Gä˜˜Q™¤Ô%Ø˜T !™WÑ$Ð&ˆDØ‰GäØ˜t A™w˜iÐ'pÐqóð ð  �—‘ ¨wÀ:Ð^b×^lÑ^lÒmˆà˜vÑ%ØÐ'Ð(Øˆùò 6s   ÁCr+   r,   Úreturnc                 óÊ   •— t        ‰| �  |i |¤Ž}t        |d   t        «      r:t	        d„ |d   D «       «      r%t	        d„ |D «       «      r|D �cg c]  }|d   ‘Œ	 c}S |S c c}w )aš  
        Generate the output text(s) using text(s) given as inputs.

        Args:
            args (`str` or `list[str]`):
                Input text for the encoder.
            return_tensors (`bool`, *optional*, defaults to `False`):
                Whether or not to include the tensors of predictions (as token indices) in the outputs.
            return_text (`bool`, *optional*, defaults to `True`):
                Whether or not to include the decoded texts in the outputs.
            clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
                Whether or not to clean up the potential extra spaces in the text output.
            truncation (`TruncationStrategy`, *optional*, defaults to `TruncationStrategy.DO_NOT_TRUNCATE`):
                The truncation strategy for the tokenization within the pipeline. `TruncationStrategy.DO_NOT_TRUNCATE`
                (default) will never truncate, but it is sometimes desirable to truncate the input to fit the model's
                max_length instead of throwing an error down the line.
            generate_kwargs:
                Additional keyword arguments to pass along to the generate method of the model (see the generate method
                corresponding to your framework [here](./text_generation)).

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

            - **generated_text** (`str`, present when `return_text=True`) -- The generated text.
            - **generated_token_ids** (`torch.Tensor` or `tf.Tensor`, present when `return_tensors=True`) -- The token
              ids of the generated text.
        r   c              3   ó<   K  — | ]  }t        |t        «      –— Œ y ­w)N)rP   rT   )Ú.0Úels     r   ú	<genexpr>z7Text2TextGenerationPipeline.__call__.<locals>.<genexpr>Â   s   è ø€ Ò:¨B”J˜r¤3×'Ñ:ùs   ‚c              3   ó8   K  — | ]  }t        |«      d k(  –— Œ y­w)r   N)r8   )r\   Úress     r   r^   z7Text2TextGenerationPipeline.__call__.<locals>.<genexpr>Ã   s   è ø€ Ò4 c”C˜“H •MÑ4ùs   ‚)r%   Ú__call__rP   rQ   Úall)r*   r+   r,   Úresultr`   r-   s        €r   ra   z$Text2TextGenerationPipeline.__call__¢   sf   ø€ ô: ‘Ñ! 4Ð2¨6Ñ2ˆä�t˜A‘w¤Ô%ÜÑ:°$°q±'Ô:Ô:ÜÑ4¨VÔ4Ô4à&,Ö-˜s�C˜“FÒ-Ð-Øˆùò .s   ÁA c                 ó0   —  | j                   |fd|i|¤Ž}|S )Nr/   )rX   )r*   rW   r/   r,   s       r   Ú
preprocessz&Text2TextGenerationPipeline.preprocessÈ   s#   € Ø)�×)Ñ)¨&ÑR¸ZÐRÈ6ÑRˆØˆr   c                 óÖ  — | j                   dk(  r|d   j                  \  }}n8| j                   dk(  r)t        j                  |d   «      j                  «       \  }}| j	                  |j                  d| j                  j                  «      |j                  d| j                  j                  «      «       d|vr| j                  |d<    | j                  j                  d
i |¤|¤Ž}|j                  d   }| j                   dk(  r( |j                  ||z  g|j                  dd  ¢­Ž }d	|iS | j                   dk(  r+t        j                  |||z  g|j                  dd  ¢­«      }d	|iS )NÚptÚ	input_idsr$   rE   rF   Úgeneration_configr   r   Ú
output_idsr   )r(   Úshaper$   ÚnumpyrJ   Úgetri   rE   rF   ÚmodelÚgenerateÚreshape)r*   Úmodel_inputsr>   Úin_brD   rj   Úout_bs          r   Ú_forwardz$Text2TextGenerationPipeline._forwardÌ   sm  € Ø�>‰>˜TÒ!Ø!-¨kÑ!:×!@Ñ!@ÑˆD‘,Ø�^‰^˜tÒ#Ü!#§¡¨,°{Ñ*CÓ!D×!JÑ!JÓ!LÑˆD�,à×ÑØØ×Ñ ¨d×.DÑ.D×.OÑ.OÓPØ×Ñ ¨d×.DÑ.D×.OÑ.OÓPô	
ð  oÑ5Ø37×3IÑ3IˆOÐ/Ñ0à(�T—Z‘Z×(Ñ(ÑK¨<ÐK¸?ÑKˆ
Ø× Ñ  Ñ#ˆØ�>‰>˜TÒ!Ø+˜×+Ñ+¨D°%¸4±-ÐWÀ*×BRÑBRÐSTÐSUÐBVÒWˆJð ˜jÐ)Ð)ð �^‰^˜tÒ#ÜŸ™ J°°uÀ±}Ð0\Àz×GWÑGWÐXYÐXZÐG[Ñ0\Ó]ˆJØ˜jÐ)Ð)r   c                 ó  — g }|d   d   D ]x  }|t         j                  k(  r| j                  › d�|i}n@|t         j                  k(  r-| j                  › d�| j                  j                  |d|¬«      i}|j                  «       Œz |S )Nrj   r   Ú
_token_idsÚ_textT)Úskip_special_tokensr1   )r   r   Úreturn_namer   r5   ÚdecodeÚappend)r*   Úmodel_outputsr0   r1   Úrecordsrj   Úrecords          r   Úpostprocessz'Text2TextGenerationPipeline.postprocessä   sŸ   € ØˆØ'¨Ñ5°aÑ8ò 	#ˆJØœj×0Ñ0Ò0Ø!×-Ñ-Ð.¨jÐ9¸:ÐF‘Ø¤
§¡Ò/à×'Ñ'Ð(¨Ð.°·±×0EÑ0EØ"Ø,0Ø5Qð 1Fó 1ð�ð �N‰N˜6Õ"ð	#ð ˆr   )NNNNNN)r   r   r   Ú__doc__Ú_pipeline_calls_generateÚ_load_processorÚ_load_image_processorÚ_load_feature_extractorÚ_load_tokenizerr   Ú_default_generation_configry   r&   rC   ÚintrJ   rX   r   rT   rQ   r   Údictra   r   ÚDO_NOT_TRUNCATEre   rt   r   r   r   Ú__classcell__©r-   s   @r   r   r      sÝ   ø„ ñ'ðR  $ÐØ€OØ!ÐØ#ÐØ€Oá!1ØØô"Ðð €Kô
ð ØØØ%)ØØó(EðT¨ð ¸#ð È3ó òð*$˜e C¨¨c© NÑ3ð $¸sð $ÀtÈDÐQTÐVYÐQYÉNÑG[õ $ðL -?×,NÑ,Nó ò*ð0 6@·_±_Ðch÷ r   r   c                   ó>   ‡ — e Zd ZdZdZˆ fd„Zdedededefd„Zˆ xZ	S )	ÚSummarizationPipelineaƒ  
    Summarize news articles and other documents.

    This summarizing pipeline can currently be loaded from [`pipeline`] using the following task identifier:
    `"summarization"`.

    The models that this pipeline can use are models that have been fine-tuned on a summarization task, which is
    currently, '*bart-large-cnn*', '*google-t5/t5-small*', '*google-t5/t5-base*', '*google-t5/t5-large*', '*google-t5/t5-3b*', '*google-t5/t5-11b*'. See the up-to-date
    list of available models on [huggingface.co/models](https://huggingface.co/models?filter=summarization). For a list
    of available parameters, see the [following
    documentation](https://huggingface.co/docs/transformers/en/main_classes/text_generation#transformers.generation.GenerationMixin.generate)

    Unless the model you're using explicitly sets these generation parameters in its configuration files
    (`generation_config.json`), the following default values will be used:
    - max_new_tokens: 256
    - num_beams: 4

    Usage:

    ```python
    # use bart in pytorch
    summarizer = pipeline("summarization")
    summarizer("An apple a day, keeps the doctor away", min_length=5, max_length=20)

    # use t5 in tf
    summarizer = pipeline("summarization", model="google-t5/t5-base", tokenizer="google-t5/t5-base", framework="tf")
    summarizer("An apple a day, keeps the doctor away", min_length=5, max_length=20)
    ```Úsummaryc                 ó"   •— t        ‰| �  |i |¤ŽS )a  
        Summarize the text(s) given as inputs.

        Args:
            documents (*str* or `list[str]`):
                One or several articles (or one list of articles) to summarize.
            return_text (`bool`, *optional*, defaults to `True`):
                Whether or not to include the decoded texts in the outputs
            return_tensors (`bool`, *optional*, defaults to `False`):
                Whether or not to include the tensors of predictions (as token indices) in the outputs.
            clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
                Whether or not to clean up the potential extra spaces in the text output.
            generate_kwargs:
                Additional keyword arguments to pass along to the generate method of the model (see the generate method
                corresponding to your framework [here](./text_generation)).

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

            - **summary_text** (`str`, present when `return_text=True`) -- The summary of the corresponding input.
            - **summary_token_ids** (`torch.Tensor` or `tf.Tensor`, present when `return_tensors=True`) -- The token
              ids of the summary.
        ©r%   ra   r)   s      €r   ra   zSummarizationPipeline.__call__  s   ø€ ô0 ‰wÑ Ð0¨Ñ0Ð0r   rD   rE   rF   rY   c           	      ó–   — ||k  rt         j                  d|› d|› d�«       ||k  r#t         j                  d|› d|› d|dz  › d�«       y	y	)
rH   zYour min_length=z' must be inferior than your max_length=ú.zYour max_length is set to z , but your input_length is only z¶. Since this is a summarization task, where outputs shorter than the input are typically wanted, you might consider decreasing max_length manually, e.g. summarizer('...', max_length=r   ú)N©ÚloggerÚwarningrI   s       r   rJ   z"SummarizationPipeline.check_inputs1  sq   € ð ˜
Ò"Ü�N‰NÐ-¨j¨\Ð9`ÐakÐ`lÐlmÐnÔoà˜*Ò$Ü�N‰NØ,¨Z¨LÐ8XÐYeÐXfð g^à^jÐnoÑ^oÐ]pÐpqðsõð %r   )
r   r   r   r€   ry   ra   r‡   ÚboolrJ   rŠ   r‹   s   @r   r�   r�   õ   s6   ø„ ñð< €Kô1ð4¨ð ¸#ð È3ð ÐSW÷ r   r�   c                   ón   ‡ — e Zd ZdZdZdededefd„Zej                  dddœˆ fd	„
Z	dˆ fd
„	Z
ˆ fd„Zˆ xZS )ÚTranslationPipelineaÍ  
    Translates from one language to another.

    This translation pipeline can currently be loaded from [`pipeline`] using the following task identifier:
    `"translation_xx_to_yy"`.

    The models that this pipeline can use are models that have been fine-tuned on a translation task. See the
    up-to-date list of available models on [huggingface.co/models](https://huggingface.co/models?filter=translation).
    For a list of available parameters, see the [following
    documentation](https://huggingface.co/docs/transformers/en/main_classes/text_generation#transformers.generation.GenerationMixin.generate)

    Unless the model you're using explicitly sets these generation parameters in its configuration files
    (`generation_config.json`), the following default values will be used:
    - max_new_tokens: 256
    - num_beams: 4

    Usage:

    ```python
    en_fr_translator = pipeline("translation_en_to_fr")
    en_fr_translator("How old are you?")
    ```ÚtranslationrD   rE   rF   c                 óL   — |d|z  kD  rt         j                  d|› d|› d�«       y)NgÍÌÌÌÌÌì?zYour input_length: z" is bigger than 0.9 * max_length: z`. You might consider increasing your max_length manually, e.g. translator('...', max_length=400)Tr”   rI   s       r   rJ   z TranslationPipeline.check_inputs\  s=   € Ø˜# 
Ñ*Ò*Ü�N‰NØ% l ^Ð3UÐV`ÐUað b^ð ^ôð r   N)r/   Úsrc_langÚtgt_langc                ó¢   •— t        | j                  dd «      r) | j                  j                  || j                  |||dœŽS t	        ‰| �  |d|iŽS )NÚ_build_translation_inputs)r;   r/   rœ   r�   r/   )Úgetattrr5   rŸ   r(   r%   rX   )r*   r/   rœ   r�   r+   r-   s        €r   re   zTranslationPipeline.preprocessd  sU   ø€ Ü�4—>‘>Ð#>ÀÔEØ;�4—>‘>×;Ñ;Ø d§n¡nÀÐV^Ðiqòð ô ‘7Ñ.°ÐLÀÑLÐLr   c                 óò   •— t        ‰	| �  di |¤Ž\  }}}|�||d<   |�||d<   |€O|€M|j                  d| j                  «      }|j	                  d«      }|rt        |«      dk(  r|d   |d<   |d   |d<   |||fS )	Nrœ   r�   ÚtaskÚ_r   r   é   r   )r%   rC   rm   r¢   Úsplitr8   )
r*   rœ   r�   r,   r?   r@   rA   r¢   Úitemsr-   s
            €r   rC   z(TranslationPipeline._sanitize_parametersl  s¦   ø€ Ü@EÁÑ@\Ñ@fÐ_eÑ@fÑ=Ð˜>Ð+=ØÐØ,4Ð˜jÑ)ØÐØ,4Ð˜jÑ)ØÐ Ð 0à—:‘:˜f d§i¡iÓ0ˆDØ—J‘J˜s“OˆEÙœ˜E›
 ašà05°a±Ð! *Ñ-Ø05°a±Ð! *Ñ-Ø  .Ð2DÐDÐDr   c                 ó"   •— t        ‰| �  |i |¤ŽS )a€  
        Translate the text(s) given as inputs.

        Args:
            args (`str` or `list[str]`):
                Texts to be translated.
            return_tensors (`bool`, *optional*, defaults to `False`):
                Whether or not to include the tensors of predictions (as token indices) in the outputs.
            return_text (`bool`, *optional*, defaults to `True`):
                Whether or not to include the decoded texts in the outputs.
            clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
                Whether or not to clean up the potential extra spaces in the text output.
            src_lang (`str`, *optional*):
                The language of the input. Might be required for multilingual models. Will not have any effect for
                single pair translation models
            tgt_lang (`str`, *optional*):
                The language of the desired output. Might be required for multilingual models. Will not have any effect
                for single pair translation models
            generate_kwargs:
                Additional keyword arguments to pass along to the generate method of the model (see the generate method
                corresponding to your framework [here](./text_generation)).

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

            - **translation_text** (`str`, present when `return_text=True`) -- The translation.
            - **translation_token_ids** (`torch.Tensor` or `tf.Tensor`, present when `return_tensors=True`) -- The
              token ids of the translation.
        r�   r)   s      €r   ra   zTranslationPipeline.__call__|  s   ø€ ô< ‰wÑ Ð0¨Ñ0Ð0r   )NN)r   r   r   r€   ry   r‡   rJ   r   r‰   re   rC   ra   rŠ   r‹   s   @r   r™   r™   @  sP   ø„ ñð0  €Kð¨ð ¸#ð È3ó ð ,>×+MÑ+MÐX\Ðgkö MõE÷ 1ð 1r   r™   )Úenumr9   Útypingr   r   Ú
generationr   Útokenization_utilsr   Úutilsr   r	   r
   r   Úbaser   r   Ú
tensorflowr$   Úmodels.auto.modeling_tf_autor   Úmodels.auto.modeling_autor   Ú
get_loggerr   r•   ÚEnumr   r   r�   r™   r   r   r   ú<module>r³      sØ   ðÛ Û ß å )Ý 3ß TÓ Tß 4ñ ÔÛå^áÔÝXà	ˆ×	Ñ	˜HÓ	%€ô�—‘ô ñ
 Ñ,¸4Ô@ÓAôV (ó Vó BðVñr Ñ,¸4Ô@ÓAôGÐ7ó Gó BðGñT Ñ,¸4Ô@ÓAôY1Ð5ó Y1ó BñY1r   