§
    Ý˜ºh¹2  ã                  ó°   — d dl mZ d dlZd dlmZ d dlmZ erddlmZ  G d„ d¦  «        Z	 G d	„ d
e	¦  «        Z
 G d„ de
¦  «        Z G d„ de
¦  «        ZdS )é    )ÚannotationsN)ÚQueue)ÚTYPE_CHECKINGé   )ÚAutoTokenizerc                  ó   — e Zd ZdZd„ Zd„ ZdS )ÚBaseStreamerzG
    Base class from which `.generate()` streamers should inherit.
    c                ó   — t          ¦   «         ‚)z;Function that is called by `.generate()` to push new tokens©ÚNotImplementedError©ÚselfÚvalues     úi/var/www/html/services/rag-service/venv/lib/python3.11/site-packages/transformers/generation/streamers.pyÚputzBaseStreamer.put    ó   € å!Ñ#Ô#Ð#ó    c                ó   — t          ¦   «         ‚)zHFunction that is called by `.generate()` to signal the end of generationr   ©r   s    r   ÚendzBaseStreamer.end$   r   r   N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   © r   r   r	   r	      s<   € € € € € ðð ð$ð $ð $ð$ð $ð $ð $ð $r   r	   c                  ó8   — e Zd ZdZddd„Zd„ Zd	„ Zddd„Zd„ ZdS )ÚTextStreamera)  
    Simple text streamer that prints the token(s) to stdout as soon as entire words are formed.

    <Tip warning={true}>

    The API for the streamer classes is still under development and may change in the future.

    </Tip>

    Parameters:
        tokenizer (`AutoTokenizer`):
            The tokenized used to decode the tokens.
        skip_prompt (`bool`, *optional*, defaults to `False`):
            Whether to skip the prompt to `.generate()` or not. Useful e.g. for chatbots.
        decode_kwargs (`dict`, *optional*):
            Additional keyword arguments to pass to the tokenizer's `decode` method.

    Examples:

        ```python
        >>> from transformers import AutoModelForCausalLM, AutoTokenizer, TextStreamer

        >>> tok = AutoTokenizer.from_pretrained("openai-community/gpt2")
        >>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
        >>> inputs = tok(["An increasing sequence: one,"], return_tensors="pt")
        >>> streamer = TextStreamer(tok)

        >>> # Despite returning the usual output, the streamer will also print the generated text to stdout.
        >>> _ = model.generate(**inputs, streamer=streamer, max_new_tokens=20)
        An increasing sequence: one, two, three, four, five, six, seven, eight, nine, ten, eleven,
        ```
    FÚ	tokenizerr   Úskip_promptÚboolc                óZ   — || _         || _        || _        g | _        d| _        d| _        d S )Nr   T)r   r   Údecode_kwargsÚtoken_cacheÚ	print_lenÚnext_tokens_are_prompt)r   r   r   r"   s       r   Ú__init__zTextStreamer.__init__K   s8   € Ø"ˆŒØ&ˆÔØ*ˆÔð ˆÔØˆŒØ&*ˆÔ#Ð#Ð#r   c                óZ  — t          |j        ¦  «        dk    r |j        d         dk    rt          d¦  «        ‚t          |j        ¦  «        dk    r|d         }| j        r| j        r	d| _        dS | j                             |                     ¦   «         ¦  «          | j        j	        | j        fi | j
        ¤Ž}|                     d¦  «        r|| j        d…         }g | _        d| _        nªt          |¦  «        dk    rU|                      t          |d         ¦  «        ¦  «        r-|| j        d…         }| xj        t          |¦  «        z  c_        nB|| j        |                     d¦  «        dz   …         }| xj        t          |¦  «        z  c_        |                      |¦  «         dS )	zm
        Receives tokens, decodes them, and prints them to stdout as soon as they form entire words.
        é   r   z'TextStreamer only supports batch size 1FNú
éÿÿÿÿú )ÚlenÚshapeÚ
ValueErrorr   r%   r#   ÚextendÚtolistr   Údecoder"   Úendswithr$   Ú_is_chinese_charÚordÚrfindÚon_finalized_text)r   r   ÚtextÚprintable_texts       r   r   zTextStreamer.putU   sŸ  € õ ˆuŒ{ÑÔ˜aÒÐ E¤K°¤N°QÒ$6Ð$6ÝÐFÑGÔGÐGÝ�”ÑÔ Ò!Ð!Ø˜!”HˆEàÔð 	 Ô ;ð 	Ø*/ˆDÔ'ØˆFð 	Ô×Ò §¢¡¤Ñ/Ô/Ð/Ø$ˆtŒ~Ô$ TÔ%5ÐLÐL¸Ô9KÐLÐLˆð �=Š=˜ÑÔð 	2Ø! $¤.Ð"2Ð"2Ô3ˆNØ!ˆDÔØˆDŒNˆNå�‰YŒY˜Š]ˆ]˜t×4Ò4µS¸¸b¼±]´]ÑCÔCˆ]Ø! $¤.Ð"2Ð"2Ô3ˆNØˆNŒN�c .Ñ1Ô1Ñ1ˆNŒNˆNð " $¤.°4·:²:¸c±?´?ÀQÑ3FÐ"FÔGˆNØˆNŒN�c .Ñ1Ô1Ñ1ˆNŒNà×Ò˜~Ñ.Ô.Ð.Ð.Ð.r   c                óì   — t          | j        ¦  «        dk    r; | j        j        | j        fi | j        ¤Ž}|| j        d…         }g | _        d| _        nd}d| _        |                      |d¬¦  «         dS )z;Flushes any remaining cache and prints a newline to stdout.r   NÚ T)Ú
stream_end)r,   r#   r   r1   r"   r$   r%   r6   )r   r7   r8   s      r   r   zTextStreamer.endw   s‹   € õ ˆtÔÑ Ô  1Ò$Ð$Ø(�4”>Ô(¨Ô)9ÐPÐP¸TÔ=OÐPÐPˆDØ! $¤.Ð"2Ð"2Ô3ˆNØ!ˆDÔØˆDŒNˆNàˆNà&*ˆÔ#Ø×Ò˜~¸$ÐÑ?Ô?Ð?Ð?Ð?r   r7   Ústrr;   c                ó2   — t          |d|sdnd¬¦  «         dS )zNPrints the new text to stdout. If the stream is ending, also prints a newline.Tr:   N)Úflushr   )Úprint©r   r7   r;   s      r   r6   zTextStreamer.on_finalized_text…   s&   € åˆd˜$¨jÐ$B B B¸dÐCÑCÔCÐCÐCÐCr   c                óÊ   — |dk    r|dk    sT|dk    r|dk    sH|dk    r|dk    s<|dk    r|dk    s0|d	k    r|d
k    s$|dk    r|dk    s|dk    r|dk    s|dk    r|dk    rdS dS )z6Checks whether CP is the codepoint of a CJK character.i N  iÿŸ  i 4  i¿M  i   iß¦ i § i?· i@· i¸ i ¸ i¯Î i ù  iÿú  i ø iú TFr   )r   Úcps     r   r3   zTextStreamer._is_chinese_char‰   s–   € ð �6Š\ˆ\˜b Fšl˜lØ�f’�  v¢ Ø�g’� "¨¢- -Ø�g’� "¨¢- -Ø�g’� "¨¢- -Ø�g’� "¨¢- -Ø�f’�  v¢ Ø�g’� "¨¢- -à�4àˆur   N©F)r   r   r   r    ©r7   r<   r;   r    )	r   r   r   r   r&   r   r   r6   r3   r   r   r   r   r   )   s‡   € € € € € ðð ðB+ð +ð +ð +ð +ð /ð  /ð  /ðD@ð @ð @ðDð Dð Dð Dð Dðð ð ð ð r   r   c                  ó>   ‡ — e Zd ZdZ	 ddˆ fd
„Zddd„Zd„ Zd„ Zˆ xZS )ÚTextIteratorStreameraè  
    Streamer that stores print-ready text in a queue, to be used by a downstream application as an iterator. This is
    useful for applications that benefit from accessing the generated text in a non-blocking way (e.g. in an interactive
    Gradio demo).

    <Tip warning={true}>

    The API for the streamer classes is still under development and may change in the future.

    </Tip>

    Parameters:
        tokenizer (`AutoTokenizer`):
            The tokenized used to decode the tokens.
        skip_prompt (`bool`, *optional*, defaults to `False`):
            Whether to skip the prompt to `.generate()` or not. Useful e.g. for chatbots.
        timeout (`float`, *optional*):
            The timeout for the text queue. If `None`, the queue will block indefinitely. Useful to handle exceptions
            in `.generate()`, when it is called in a separate thread.
        decode_kwargs (`dict`, *optional*):
            Additional keyword arguments to pass to the tokenizer's `decode` method.

    Examples:

        ```python
        >>> from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
        >>> from threading import Thread

        >>> tok = AutoTokenizer.from_pretrained("openai-community/gpt2")
        >>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
        >>> inputs = tok(["An increasing sequence: one,"], return_tensors="pt")
        >>> streamer = TextIteratorStreamer(tok)

        >>> # Run the generation in a separate thread, so that we can fetch the generated text in a non-blocking way.
        >>> generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=20)
        >>> thread = Thread(target=model.generate, kwargs=generation_kwargs)
        >>> thread.start()
        >>> generated_text = ""
        >>> for new_text in streamer:
        ...     generated_text += new_text
        >>> generated_text
        'An increasing sequence: one, two, three, four, five, six, seven, eight, nine, ten, eleven,'
        ```
    FNr   r   r   r    Útimeoutúfloat | Nonec                ó€   •—  t          ¦   «         j        ||fi |¤Ž t          ¦   «         | _        d | _        || _        d S ©N)Úsuperr&   r   Ú
text_queueÚstop_signalrG   ©r   r   r   rG   r"   Ú	__class__s        €r   r&   zTextIteratorStreamer.__init__Ð   sD   ø€ ð 	�‰ŒÔ˜ KÐAÐA°=ÐAÐAÐAÝ™'œ'ˆŒØˆÔØˆŒˆˆr   r7   r<   r;   c                óœ   — | j                              || j        ¬¦  «         |r(| j                              | j        | j        ¬¦  «         dS dS )ú\Put the new text in the queue. If the stream is ending, also put a stop signal in the queue.©rG   N)rL   r   rG   rM   r@   s      r   r6   z&TextIteratorStreamer.on_finalized_textØ   sZ   € àŒ×Ò˜D¨$¬,ÐÑ7Ô7Ð7Øð 	HØŒO×Ò Ô 0¸$¼,ÐÑGÔGÐGÐGÐGð	Hð 	Hr   c                ó   — | S rJ   r   r   s    r   Ú__iter__zTextIteratorStreamer.__iter__Þ   ó   € Øˆr   c                óx   — | j                              | j        ¬¦  «        }|| j        k    rt	          ¦   «         ‚|S ©NrR   )rL   ÚgetrG   rM   ÚStopIterationr   s     r   Ú__next__zTextIteratorStreamer.__next__á   s9   € Ø”×#Ò#¨D¬LÐ#Ñ9Ô9ˆØ�DÔ$Ò$Ð$Ý‘/”/Ð!àˆLr   ©FN©r   r   r   r    rG   rH   rC   rD   )	r   r   r   r   r&   r6   rT   rZ   Ú__classcell__©rO   s   @r   rF   rF   ¢   s�   ø€ € € € € ð+ð +ð\ \`ðð ð ð ð ð ð ðHð Hð Hð Hð Hðð ð ðð ð ð ð ð ð r   rF   c                  ó>   ‡ — e Zd ZdZ	 ddˆ fd
„Zddd„Zd„ Zd„ Zˆ xZS )ÚAsyncTextIteratorStreamera'	  
    Streamer that stores print-ready text in a queue, to be used by a downstream application as an async iterator.
    This is useful for applications that benefit from accessing the generated text asynchronously (e.g. in an
    interactive Gradio demo).

    <Tip warning={true}>

    The API for the streamer classes is still under development and may change in the future.

    </Tip>

    Parameters:
        tokenizer (`AutoTokenizer`):
            The tokenized used to decode the tokens.
        skip_prompt (`bool`, *optional*, defaults to `False`):
            Whether to skip the prompt to `.generate()` or not. Useful e.g. for chatbots.
        timeout (`float`, *optional*):
            The timeout for the text queue. If `None`, the queue will block indefinitely. Useful to handle exceptions
            in `.generate()`, when it is called in a separate thread.
        decode_kwargs (`dict`, *optional*):
            Additional keyword arguments to pass to the tokenizer's `decode` method.

    Raises:
        TimeoutError: If token generation time exceeds timeout value.

    Examples:

        ```python
        >>> from transformers import AutoModelForCausalLM, AutoTokenizer, AsyncTextIteratorStreamer
        >>> from threading import Thread
        >>> import asyncio

        >>> tok = AutoTokenizer.from_pretrained("openai-community/gpt2")
        >>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
        >>> inputs = tok(["An increasing sequence: one,"], return_tensors="pt")

        >>> # Run the generation in a separate thread, so that we can fetch the generated text in a non-blocking way.
        >>> async def main():
        ...     # Important: AsyncTextIteratorStreamer must be initialized inside a coroutine!
        ...     streamer = AsyncTextIteratorStreamer(tok)
        ...     generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=20)
        ...     thread = Thread(target=model.generate, kwargs=generation_kwargs)
        ...     thread.start()
        ...     generated_text = ""
        ...     async for new_text in streamer:
        ...         generated_text += new_text
        >>>     print(generated_text)
        >>> asyncio.run(main())
        An increasing sequence: one, two, three, four, five, six, seven, eight, nine, ten, eleven,
        ```
    FNr   r   r   r    rG   rH   c                óî   •—  t          ¦   «         j        ||fi |¤Ž t          j        ¦   «         | _        d | _        || _        t          j        ¦   «         | _        t          t          d¦  «        | _
        d S )NrG   )rK   r&   Úasyncior   rL   rM   rG   Úget_running_loopÚloopÚhasattrÚhas_asyncio_timeoutrN   s        €r   r&   z"AsyncTextIteratorStreamer.__init__  sj   ø€ ð 	�‰ŒÔ˜ KÐAÐA°=ÐAÐAÐAÝ!œ-™/œ/ˆŒØˆÔØˆŒÝÔ,Ñ.Ô.ˆŒ	Ý#*­7°IÑ#>Ô#>ˆÔ Ð Ð r   r7   r<   r;   c                ó¬   — | j                              | j        j        |¦  «         |r,| j                              | j        j        | j        ¦  «         dS dS )rQ   N)rd   Úcall_soon_threadsaferL   Ú
put_nowaitrM   r@   s      r   r6   z+AsyncTextIteratorStreamer.on_finalized_text(  sZ   € àŒ	×&Ò& t¤Ô'AÀ4ÑHÔHÐHØð 	YØŒI×*Ò*¨4¬?Ô+EÀtÔGWÑXÔXÐXÐXÐXð	Yð 	Yr   c                ó   — | S rJ   r   r   s    r   Ú	__aiter__z#AsyncTextIteratorStreamer.__aiter__.  rU   r   c              ƒ  óÄ  K  — 	 | j         rct          j        | j        ¦  «        4 ƒd {V —† | j                             ¦   «         ƒ d {V —†}d d d ¦  «        ƒd {V —† n# 1 ƒd {V —†swxY w Y   n8t          j        | j                             ¦   «         | j        ¬¦  «        ƒ d {V —†}|| j        k    rt          ¦   «         ‚|S # t          j        $ r t          ¦   «         ‚w xY wrW   )	rf   rb   rG   rL   rX   Úwait_forrM   ÚStopAsyncIterationÚTimeoutErrorr   s     r   Ú	__anext__z#AsyncTextIteratorStreamer.__anext__1  s‚  è è € ð	ØÔ'ð \Ý"œ?¨4¬<Ñ8Ô8ð 8ð 8ð 8ð 8ð 8ð 8ð 8ð 8Ø"&¤/×"5Ò"5Ñ"7Ô"7Ð7Ð7Ð7Ð7Ð7Ð7�Eð8ð 8ð 8ñ 8ô 8ð 8ð 8ð 8ð 8ð 8ð 8ð 8ð 8ð 8ð 8ð 8ð 8ð 8ð 8ð 8ð 8ð 8ð 8øøøð 8ð 8ð 8ð 8øõ &Ô.¨t¬×/BÒ/BÑ/DÔ/DÈdÌlÐ[Ñ[Ô[Ð[Ð[Ð[Ð[Ð[Ð[�ð ˜Ô(Ò(Ð(Ý(Ñ*Ô*Ð*à�øõ Ô#ð 	!ð 	!ð 	!Ý‘.”.Ð ð	!øøøs.   „&C ª AÁ
C Á
A&Á&C Á)A&Á*<C ÃCr[   r\   rC   rD   )	r   r   r   r   r&   r6   rk   rp   r]   r^   s   @r   r`   r`   é   s�   ø€ € € € € ð2ð 2ðj \`ð?ð ?ð ?ð ?ð ?ð ?ð ?ðYð Yð Yð Yð Yðð ð ðð ð ð ð ð ð r   r`   )Ú
__future__r   rb   Úqueuer   Útypingr   Úmodels.autor   r	   r   rF   r`   r   r   r   ú<module>ru      s.  ðð  #Ð "Ð "Ð "Ð "Ð "à €€€Ø Ð Ð Ð Ð Ð Ø  Ð  Ð  Ð  Ð  Ð  ð ð ,Ø+Ð+Ð+Ð+Ð+Ð+ð$ð $ð $ð $ð $ñ $ô $ð $ðvð vð vð vð v�<ñ vô vð vðrDð Dð Dð Dð D˜<ñ Dô Dð DðNUð Uð Uð Uð U ñ Uô Uð Uð Uð Ur   