
"""simple docstring"""

from queue import Queue
from typing import TYPE_CHECKING, Optional


if TYPE_CHECKING:
					from ..models.auto import AutoTokenizer






class 	_lowercase       :




	def       _UpperCamelCase   (			self		,			UpperCAmelCase_ )		->							int:
			raise NotImplementedError()




	def       _UpperCamelCase   (			self )		->							str:
			raise NotImplementedError()






class 	_lowercase       (    __lowercase		):




	def __init__(			self		,			UpperCAmelCase_		,			UpperCAmelCase_ = False		,			**UpperCAmelCase_ )		->							int:
			lowerCamelCase					:      List[Any]          =   tokenizer
			lowerCamelCase					:      Optional[Any]          =   skip_prompt
			lowerCamelCase					:      int          =   decode_kwargs

			# variables used in the streaming process
			lowerCamelCase					:      int          =   []
			lowerCamelCase					:      Union[str, Any]          =   0
			lowerCamelCase					:      int          =   True




	def       _UpperCamelCase   (			self		,			UpperCAmelCase_ )		->							List[str]:
			if len(value.shape ) > 1 and value.shape[0] > 1:
					raise ValueError('TextStreamer only supports batch size 1' )
			elif len(value.shape ) > 1:
					lowerCamelCase					:      List[str]          =   value[0]

			if self.skip_prompt and self.next_tokens_are_prompt:
					lowerCamelCase					:      Dict          =   False
					return

			# Add the new token to the cache and decodes the entire thing.
			self.token_cache.extend(value.tolist() )
			lowerCamelCase					:      Tuple          =   self.tokenizer.decode(self.token_cache		,			**self.decode_kwargs )

			# After the symbol for a new line, we flush the cache.
			if text.endswith('\n' ):
					lowerCamelCase					:      List[str]          =   text[self.print_len :]
					lowerCamelCase					:      Optional[Any]          =   []
					lowerCamelCase					:      Union[str, Any]          =   0
			# If the last token is a CJK character, we print the characters.
			elif len(_a ) > 0 and self._is_chinese_char(ord(text[-1] ) ):
					lowerCamelCase					:      int          =   text[self.print_len :]
					self.print_len += len(_a )
			# Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words,
			# which may change with the subsequent token -- there are probably smarter ways to do this!)
			else:
					lowerCamelCase					:      List[Any]          =   text[self.print_len : text.rfind(' ' ) + 1]
					self.print_len += len(_a )

			self.on_finalized_text(_a )




	def       _UpperCamelCase   (			self )		->							Tuple:
			# Flush the cache, if it exists
			if len(self.token_cache ) > 0:
					lowerCamelCase					:      List[str]          =   self.tokenizer.decode(self.token_cache		,			**self.decode_kwargs )
					lowerCamelCase					:      Tuple          =   text[self.print_len :]
					lowerCamelCase					:      Union[str, Any]          =   []
					lowerCamelCase					:      Union[str, Any]          =   0
			else:
					lowerCamelCase					:      str          =   ''

			lowerCamelCase					:      Any          =   True
			self.on_finalized_text(_a		,			stream_end=_a )




	def       _UpperCamelCase   (			self		,			UpperCAmelCase_		,			UpperCAmelCase_ = False )		->							Union[str, Any]:
			print(_a		,			flush=_a		,			end='' if not stream_end else None )




	def       _UpperCamelCase   (			self		,			UpperCAmelCase_ )		->							str:
			# This defines a "chinese character" as anything in the CJK Unicode block:
			#   https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
			#
			# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
			# despite its name. The modern Korean Hangul alphabet is a different block,
			# as is Japanese Hiragana and Katakana. Those alphabets are used to write
			# space-separated words, so they are not treated specially and handled
			# like the all of the other languages.
			if (
			    (cp >= 0X4e_00 and cp <= 0X9f_ff)
			    or (cp >= 0X34_00 and cp <= 0X4d_bf)  #
			    or (cp >= 0X2_00_00 and cp <= 0X2_a6_df)  #
			    or (cp >= 0X2_a7_00 and cp <= 0X2_b7_3f)  #
			    or (cp >= 0X2_b7_40 and cp <= 0X2_b8_1f)  #
			    or (cp >= 0X2_b8_20 and cp <= 0X2_ce_af)  #
			    or (cp >= 0Xf9_00 and cp <= 0Xfa_ff)
			    or (cp >= 0X2_f8_00 and cp <= 0X2_fa_1f)  #
			):  #
					return True

			return False






class 	_lowercase       (    __lowercase		):




	def __init__(			self		,			UpperCAmelCase_		,			UpperCAmelCase_ = False		,			UpperCAmelCase_ = None		,			**UpperCAmelCase_ )		->							Any:
			super().__init__(_a		,			_a		,			**_a )
			lowerCamelCase					:      Optional[Any]          =   Queue()
			lowerCamelCase					:      Optional[Any]          =   None
			lowerCamelCase					:      Dict          =   timeout




	def       _UpperCamelCase   (			self		,			UpperCAmelCase_		,			UpperCAmelCase_ = False )		->							int:
			self.text_queue.put(_a		,			timeout=self.timeout )
			if stream_end:
					self.text_queue.put(self.stop_signal		,			timeout=self.timeout )




	def __iter__(			self )		->							str:
			return self




	def       _UpperCamelCase   (			self )		->							int:
			lowerCamelCase					:      str          =   self.text_queue.get(timeout=self.timeout )
			if value == self.stop_signal:
					raise StopIteration()
			else:
					return value








"""simple docstring"""

import os
import sys
from contextlib import contextmanager


# Windows only
if os.name == "nt":
					import ctypes
					import msvcrt  # noqa






					class 	_lowercase       (    ctypes.Structure		):
						# _fields is a specific attr expected by ctypes
						lowercase_				=     [('size', ctypes.c_int), ('visible', ctypes.c_byte)]
def 		UpperCAmelCase (		):





		'''simple docstring'''


		if os.name == "nt":
				lowerCamelCase					:      Optional[int]          =   CursorInfo()
				lowerCamelCase					:      Union[str, Any]          =   ctypes.windll.kernelaa.GetStdHandle(-11      )
				ctypes.windll.kernelaa.GetConsoleCursorInfo(a_,						ctypes.byref(a_      )      )
				lowerCamelCase					:      Dict          =   False
				ctypes.windll.kernelaa.SetConsoleCursorInfo(a_,						ctypes.byref(a_      )      )
		elif os.name == "posix":
				sys.stdout.write('\033[?25l'      )
				sys.stdout.flush()
def 		UpperCAmelCase (		):





		'''simple docstring'''


		if os.name == "nt":
				lowerCamelCase					:      List[str]          =   CursorInfo()
				lowerCamelCase					:      List[Any]          =   ctypes.windll.kernelaa.GetStdHandle(-11      )
				ctypes.windll.kernelaa.GetConsoleCursorInfo(a_,						ctypes.byref(a_      )      )
				lowerCamelCase					:      Optional[Any]          =   True
				ctypes.windll.kernelaa.SetConsoleCursorInfo(a_,						ctypes.byref(a_      )      )
		elif os.name == "posix":
				sys.stdout.write('\033[?25h'      )
				sys.stdout.flush()





@contextmanager
def 		UpperCAmelCase (		):





		'''simple docstring'''


		try:
				hide_cursor()
				yield
		finally:
				show_cursor()






