



'''simple docstring'''





from queue import Queue
from typing import TYPE_CHECKING, Optional


if TYPE_CHECKING:
  from ..models.auto import AutoTokenizer






class __A    :



 '''simple docstring'''







 def       a__						(self				,     A )					->  Union[str, Any]:


      """simple docstring"""



      raise NotImplementedError()



 def       a__						(self )					->  Dict:


      """simple docstring"""



      raise NotImplementedError()






class __A    (						A		):



 '''simple docstring'''







 def __init__(self				,     A				,     A = False				,     **A )					->  Union[str, Any]:


      """simple docstring"""



      _a											=						tokenizer
      _a											=						skip_prompt
      _a											=						decode_kwargs

      # variables used in the streaming process
      _a											=						[]
      _a											=						0
      _a											=						True



 def       a__						(self				,     A )					->  Dict:


      """simple docstring"""



      if len(value.shape ) > 1 and value.shape[0] > 1:
           raise ValueError('''TextStreamer only supports batch size 1''' )
      elif len(value.shape ) > 1:
           _a											=						value[0]

      if self.skip_prompt and self.next_tokens_are_prompt:
           _a											=						False
           return

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

      # After the symbol for a new line, we flush the cache.
      if text.endswith('''\n''' ):
           _a											=						text[self.print_len :]
           _a											=						[]
           _a											=						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] ) ):
           _a											=						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:
           _a											=						text[self.print_len : text.rfind(''' ''' ) + 1]
           self.print_len += len(A )

      self.on_finalized_text(A )



 def       a__						(self )					->  Any:


      """simple docstring"""



      if len(self.token_cache ) > 0:
           _a											=						self.tokenizer.decode(self.token_cache				,     **self.decode_kwargs )
           _a											=						text[self.print_len :]
           _a											=						[]
           _a											=						0
      else:
           _a											=						''''''

      _a											=						True
      self.on_finalized_text(A				,     stream_end=A )



 def       a__						(self				,     A				,     A = False )					->  Optional[int]:


      """simple docstring"""



      print(A				,     flush=A				,     end='''''' if not stream_end else None )



 def       a__						(self				,     A )					->  Tuple:


      """simple docstring"""



      if (
          (cp >= 0x4_E00 and cp <= 0x9_FFF)
          or (cp >= 0x3_400 and cp <= 0x4_DBF)  #
          or (cp >= 0x20_000 and cp <= 0x2A_6DF)  #
          or (cp >= 0x2A_700 and cp <= 0x2B_73F)  #
          or (cp >= 0x2B_740 and cp <= 0x2B_81F)  #
          or (cp >= 0x2B_820 and cp <= 0x2C_EAF)  #
          or (cp >= 0xF_900 and cp <= 0xF_AFF)
          or (cp >= 0x2F_800 and cp <= 0x2F_A1F)  #
      ):  #
           return True

      return False






class __A    (						A		):



 '''simple docstring'''







 def __init__(self				,     A				,     A = False				,     A = None				,     **A )					->  Any:


      """simple docstring"""



      super().__init__(A				,     A				,     **A )
      _a											=						Queue()
      _a											=						None
      _a											=						timeout



 def       a__						(self				,     A				,     A = False )					->  str:


      """simple docstring"""



      self.text_queue.put(A				,     timeout=self.timeout )
      if stream_end:
           self.text_queue.put(self.stop_signal				,     timeout=self.timeout )



 def __iter__(self )					->  Union[str, Any]:


      """simple docstring"""



      return self



 def       a__						(self )					->  List[str]:


      """simple docstring"""



      _a											=						self.text_queue.get(timeout=self.timeout )
      if value == self.stop_signal:
           raise StopIteration()
      else:
           return value








'''simple docstring'''





from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
  import tensorflow as tf

  from ..tf_utils import stable_softmax


if is_torch_available():
  import torch


lowercase_	 =						logging.get_logger(__name__)






@add_end_docstrings(
    A     ,     R'\n        top_k (`int`, defaults to 5):\n            The number of predictions to return.\n        targets (`str` or `List[str]`, *optional*):\n            When passed, the model will limit the scores to the passed targets instead of looking up in the whole\n            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting\n            token will be used (with a warning, and that might be slower).\n\n    '     ,     )
class __A    (						A		):



 '''simple docstring'''







 def       a__						(self				,     A )					->  np.ndarray:


      """simple docstring"""



      if self.framework == "tf":
           _a											=						tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()
      elif self.framework == "pt":
           _a											=						torch.nonzero(input_ids == self.tokenizer.mask_token_id				,     as_tuple=A )
      else:
           raise ValueError('''Unsupported framework''' )
      return masked_index



 def       a__						(self				,     A )					->  np.ndarray:


      """simple docstring"""



      _a											=						self.get_masked_index(A )
      _a											=						np.prod(masked_index.shape )
      if numel < 1:
           raise PipelineException(
               '''fill-mask'''				,     self.model.base_model_prefix				,     f'''No mask_token ({self.tokenizer.mask_token}) found on the input'''				,     )



 def       a__						(self				,     A )					->  Optional[int]:


      """simple docstring"""



      if isinstance(A				,     A ):
           for model_input in model_inputs:
                self._ensure_exactly_one_mask_token(model_input['''input_ids'''][0] )
      else:
           for input_ids in model_inputs["input_ids"]:
                self._ensure_exactly_one_mask_token(A )



 def       a__						(self				,     A				,     A=None				,     **A )					->  Dict[str, GenericTensor]:


      """simple docstring"""



      if return_tensors is None:
           _a											=						self.framework
      _a											=						self.tokenizer(A				,     return_tensors=A )
      self.ensure_exactly_one_mask_token(A )
      return model_inputs



 def       a__						(self				,     A )					->  Optional[Any]:


      """simple docstring"""



      _a											=						self.model(**A )
      _a											=						model_inputs['''input_ids''']
      return model_outputs



 def       a__						(self				,     A				,     A=5				,     A=None )					->  Tuple:


      """simple docstring"""



      if target_ids is not None and target_ids.shape[0] < top_k:
           _a											=						target_ids.shape[0]
      _a											=						model_outputs['''input_ids'''][0]
      _a											=						model_outputs['''logits''']

      if self.framework == "tf":
           _a											=						tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()[:, 0]

           _a											=						outputs.numpy()

           _a											=						outputs[0, masked_index, :]
           _a											=						stable_softmax(A				,     axis=-1 )
           if target_ids is not None:
                _a											=						tf.gather_nd(tf.squeeze(A				,     0 )				,     target_ids.reshape(-1				,     1 ) )
                _a											=						tf.expand_dims(A				,     0 )

           _a											=						tf.math.top_k(A				,     k=A )
           _a						,					_a											=						topk.values.numpy(), topk.indices.numpy()
      else:
           _a											=						torch.nonzero(input_ids == self.tokenizer.mask_token_id				,     as_tuple=A ).squeeze(-1 )
           # Fill mask pipeline supports only one ${mask_token} per sample

           _a											=						outputs[0, masked_index, :]
           _a											=						logits.softmax(dim=-1 )
           if target_ids is not None:
                _a											=						probs[..., target_ids]

           _a						,					_a											=						probs.topk(A )

      _a											=						[]
      _a											=						values.shape[0] == 1
      for i, (_values, _predictions) in enumerate(zip(values.tolist()				,     predictions.tolist() ) ):
           _a											=						[]
           for v, p in zip(_values				,     _predictions ):
                # Copy is important since we're going to modify this array in place
                _a											=						input_ids.numpy().copy()
                if target_ids is not None:
                     _a											=						target_ids[p].tolist()

                _a											=						p
                # Filter padding out:
                _a											=						tokens[np.where(tokens != self.tokenizer.pad_token_id )]
                # Originally we skip special tokens to give readable output.
                # For multi masks though, the other [MASK] would be removed otherwise
                # making the output look odd, so we add them back
                _a											=						self.tokenizer.decode(A				,     skip_special_tokens=A )
                _a											=						{'''score''': v, '''token''': p, '''token_str''': self.tokenizer.decode([p] ), '''sequence''': sequence}
                row.append(A )
           result.append(A )
      if single_mask:
           return result[0]
      return result



 def       a__						(self				,     A				,     A=None )					->  Optional[Any]:


      """simple docstring"""



      if isinstance(A				,     A ):
           _a											=						[targets]
      try:
           _a											=						self.tokenizer.get_vocab()
      except Exception:
           _a											=						{}
      _a											=						[]
      for target in targets:
           _a											=						vocab.get(A				,     A )
           if id_ is None:
                _a											=						self.tokenizer(
                    A				,     add_special_tokens=A				,     return_attention_mask=A				,     return_token_type_ids=A				,     max_length=1				,     truncation=A				,     )['''input_ids''']
                if len(A ) == 0:
                     logger.warning(
                         f'''The specified target token `{target}` does not exist in the model vocabulary. '''
                         '''We cannot replace it with anything meaningful, ignoring it''' )
                     continue
                _a											=						input_ids[0]
                # XXX: If users encounter this pass
                # it becomes pretty slow, so let's make sure
                # The warning enables them to fix the input to
                # get faster performance.
                logger.warning(
                    f'''The specified target token `{target}` does not exist in the model vocabulary. '''
                    f'''Replacing with `{self.tokenizer.convert_ids_to_tokens(id_ )}`.''' )
           target_ids.append(id_ )
      _a											=						list(set(A ) )
      if len(A ) == 0:
           raise ValueError('''At least one target must be provided when passed.''' )
      _a											=						np.array(A )
      return target_ids



 def       a__						(self				,     A=None				,     A=None )					->  List[str]:


      """simple docstring"""



      _a											=						{}

      if targets is not None:
           _a											=						self.get_target_ids(A				,     A )
           _a											=						target_ids

      if top_k is not None:
           _a											=						top_k

      if self.tokenizer.mask_token_id is None:
           raise PipelineException(
               '''fill-mask'''				,     self.model.base_model_prefix				,     '''The tokenizer does not define a `mask_token`.''' )
      return {}, {}, postprocess_params



 def __call__(self				,     A				,     *A				,     **A )					->  str:


      """simple docstring"""



      _a											=						super().__call__(A				,     **A )
      if isinstance(A				,     A ) and len(A ) == 1:
           return outputs[0]
      return outputs



