Ë
    S^(hâ2  ã                  óš   — d dl mZ d dlZd dlmZ d dlmZ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y)é    )ÚannotationsN)ÚQueue)ÚTYPE_CHECKINGÚOptionalé   )ÚAutoTokenizerc                  ó   — e Zd ZdZd„ Zd„ Zy)Ú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     ú_/var/www/skyplay_api_hub/venv/lib/python3.12/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                  ó6   — e Zd ZdZdd	d„Zd„ Zd„ Zdd
d„Zd„ Zy)Ú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,
        ```
    c                óX   — || _         || _        || _        g | _        d| _        d| _        y )Nr   T)Ú	tokenizerÚskip_promptÚdecode_kwargsÚtoken_cacheÚ	print_lenÚnext_tokens_are_prompt)r   r    r!   r"   s       r   Ú__init__zTextStreamer.__init__K   s2   € Ø"ˆŒØ&ˆÔØ*ˆÔð ˆÔØˆŒØ&*ˆÕ#r   c                óL  — t        |j                  «      dkD  r|j                  d   dkD  rt        d«      ‚t        |j                  «      dkD  r|d   }| j                  r| j                  rd| _        y| j
                  j                  |j                  «       «        | j                  j                  | j
                  fi | j                  ¤Ž}|j                  d«      r|| j                  d }g | _        d| _        n˜t        |«      dkD  rK| j                  t        |d   «      «      r.|| j                  d }| xj                  t        |«      z  c_        n?|| j                  |j                  d«      dz    }| xj                  t        |«      z  c_        | j!                  |«       y)	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¡K°¡N°QÒ$6ÜÐFÓGÐGÜ�—‘Ó Ò!Ø˜!‘HˆEà×Ò × ;Ò ;Ø*/ˆDÔ'Øð 	×Ñ×Ñ §¡£Ô/Ø$ˆt�~‰~×$Ñ$ T×%5Ñ%5ÑL¸×9KÑ9KÑLˆð �=‰=˜ÔØ! $§.¡.Ð"2Ð3ˆNØ!ˆDÔØˆD�Nä�‹Y˜Š]˜t×4Ñ4´S¸¸b¹³]ÔCØ! $§.¡.Ð"2Ð3ˆNØ�NŠNœc .Ó1Ñ1ŽNð " $§.¡.°4·:±:¸c³?ÀQÑ3FÐGˆNØ�NŠNœc .Ó1Ñ1�Nà×Ñ˜~Õ.r   c                ó
  — t        | j                  «      dkD  rO | j                  j                  | j                  fi | j                  ¤Ž}|| j
                  d }g | _        d| _        nd}d| _        | j                  |d¬«       y)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Ñ)9ÑP¸T×=OÑ=OÑPˆDØ! $§.¡.Ð"2Ð3ˆNØ!ˆDÔØˆD�NàˆNà&*ˆÔ#Ø×Ñ˜~¸$ÐÕ?r   c                ó4   — t        |d|sd¬«       yd¬«       y)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ÖC¸dÖCr   c                ó¦   — |dk\  r|dk  sF|dk\  r|dk  s<|dk\  r|dk  s2|dk\  r|dk  s(|d	k\  r|d
k  s|dk\  r|dk  s|dk\  r|dk  s
|dk\  r|dk  ryy)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‰   sr   € ð �6Š\˜b FšlØ�f’  v¢Ø�g’ "¨¢-Ø�g’ "¨¢-Ø�g’ "¨¢-Ø�g’ "¨¢-Ø�f’  v¢Ø�g’ "¨¢-ààr   N©F)r    ú'AutoTokenizer'r!   Úbool©r7   Ústrr;   rD   )	r   r   r   r   r&   r   r   r6   r3   r   r   r   r   r   )   s$   „ ñôB+ò /òD@ôDór   r   c                  óH   ‡ — 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 acessing 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,'
        ```
    c                ób   •— t        ‰| �  ||fi |¤Ž t        «       | _        d | _        || _        y ©N)Úsuperr&   r   Ú
text_queueÚstop_signalÚtimeout©r   r    r!   rN   r"   Ú	__class__s        €r   r&   zTextIteratorStreamer.__init__Ð   s1   ø€ ô 	‰Ñ˜ KÑA°=ÒAÜ›'ˆŒØˆÔØˆ�r   c                óº   — | j                   j                  || j                  ¬«       |r2| j                   j                  | j                  | j                  ¬«       yy)ú\Put the new text in the queue. If the stream is ending, also put a stop signal in the queue.©rN   N)rL   r   rN   rM   r?   s      r   r6   z&TextIteratorStreamer.on_finalized_textØ   sF   € à�‰×Ñ˜D¨$¯,©,ÐÔ7ÙØ�O‰O×Ñ × 0Ñ 0¸$¿,¹,ÐÕGð r   c                ó   — | S rJ   r   r   s    r   Ú__iter__zTextIteratorStreamer.__iter__Þ   ó   € Øˆr   c                ó„   — | j                   j                  | j                  ¬«      }|| j                  k(  r
t	        «       ‚|S ©NrS   )rL   ÚgetrN   rM   ÚStopIterationr   s     r   Ú__next__zTextIteratorStreamer.__next__á   s8   € Ø—‘×#Ñ#¨D¯L©LÐ#Ó9ˆØ�D×$Ñ$Ò$Ü“/Ð!àˆLr   ©FN©r    rC   r!   rD   rN   zOptional[float]rB   rE   )	r   r   r   r   r&   r6   rU   r[   Ú__classcell__©rP   s   @r   rH   rH   ¢   s=   ø„ ñ+ð\ aeðØ(ðØ7;ðØN]õôHòör   rH   c                  óH   ‡ — 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 acessing 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,
        ```
    c                óÒ   •— t        ‰| �  ||fi |¤Ž t        j                  «       | _        d | _        || _        t        j                  «       | _        t        t        d«      | _
        y )NrN   )rK   r&   Úasyncior   rL   rM   rN   Úget_running_loopÚloopÚhasattrÚhas_asyncio_timeoutrO   s        €r   r&   z"AsyncTextIteratorStreamer.__init__  sT   ø€ ô 	‰Ñ˜ KÑA°=ÒAÜ!Ÿ-™-›/ˆŒØˆÔØˆŒÜ×,Ñ,Ó.ˆŒ	Ü#*¬7°IÓ#>ˆÕ r   c                óÞ   — | j                   j                  | j                  j                  |«       |r;| j                   j                  | j                  j                  | j                  «       yy)rR   N)re   Úcall_soon_threadsaferL   Ú
put_nowaitrM   r?   s      r   r6   z+AsyncTextIteratorStreamer.on_finalized_text(  sL   € à�	‰	×&Ñ& t§¡×'AÑ'AÀ4ÔHÙØ�I‰I×*Ñ*¨4¯?©?×+EÑ+EÀt×GWÑGWÕXð r   c                ó   — | S rJ   r   r   s    r   Ú	__aiter__z#AsyncTextIteratorStreamer.__aiter__.  rV   r   c              ƒ  ó  K  — 	 | j                   r[t        j                  | j                  «      4 ƒd {  –—†  | j                  j	                  «       ƒ d {  –—† }d d d «      ƒd {  –—†  nAt        j
                  | j                  j	                  «       | j                  ¬«      ƒ d {  –—† }| j                  k(  r
t        «       ‚|S 7 Œ“7 Œs7 Œe# 1 ƒd {  –—†7  sw Y   Œ3xY w7 Œ:# t        j                  $ r t        «       ‚w xY w­wrX   )	rg   rc   rN   rL   rY   Úwait_forrM   ÚStopAsyncIterationÚTimeoutErrorr   s     r   Ú	__anext__z#AsyncTextIteratorStreamer.__anext__1  sÚ   è ø€ ð	Ø×'Ò'Ü"Ÿ?™?¨4¯<©<Ó8÷ 8ñ 8Ø"&§/¡/×"5Ñ"5Ó"7×7�E÷8÷ 8ð 8ô &×.Ñ.¨t¯©×/BÑ/BÓ/DÈdÏlÉlÔ[×[�ð ˜×(Ñ(Ò(Ü(Ó*Ð*à�ð8øØ7øð8ø÷ 8÷ 8ñ 8úð \ùÜ×#Ñ#ò 	!Ü“.Ð ð	!üs€   ‚D„/C$ ³C´C$ ·CÁC	ÁCÁC$ Á%CÁ&AC$ Â'C"Â(C$ Â,DÃC$ Ã	CÃC$ ÃCÃCÃCÃC$ Ã$DÄDr\   r]   rB   rE   )	r   r   r   r   r&   r6   rl   rq   r^   r_   s   @r   ra   ra   é   s=   ø„ ñ2ðj aeð?Ø(ð?Ø7;ð?ØN]õ?ôYòör   ra   )Ú
__future__r   rc   Úqueuer   Útypingr   r   Úmodels.autor   r
   r   rH   ra   r   r   r   ú<module>rv      sQ   ðõ  #ã Ý ß *ñ Ý+÷$ñ $ôv�<ô vôrD˜<ô DôNU õ Ur   