


import inspect

import jax
import jax.lax as lax
import jax.numpy as jnp

from ..utils import add_start_docstrings
from ..utils.logging import get_logger


__UpperCamelCase    :						Tuple     =							get_logger(__name__)


__UpperCamelCase    :						Optional[int]     =							R'\n    Args:\n        input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):\n            Indices of input sequence tokens in the vocabulary.\n\n            Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n            [`PreTrainedTokenizer.__call__`] for details.\n\n            [What are input IDs?](../glossary#input-ids)\n        scores (`jnp.ndarray` of shape `(batch_size, config.vocab_size)`):\n            Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam\n            search or log softmax for each vocabulary token when using beam search\n        kwargs (`Dict[str, Any]`, *optional*):\n            Additional logits processor specific kwargs.\n\n    Return:\n        `jnp.ndarray` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.\n\n'



class 							_UpperCamelCase :

 '''simple docstring'''







 @add_start_docstrings(lowercase_							)
 def __call__(  self  : List[Any]       ,  _lowerCamelCase  : jnp.ndarray       ,  _lowerCamelCase  : jnp.ndarray							):






       '''simple docstring'''



       raise NotImplementedError(
           F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called."""							)



class 							_UpperCamelCase :

 '''simple docstring'''







 @add_start_docstrings(lowercase_							)
 def __call__(  self  : Tuple       ,  _lowerCamelCase  : jnp.ndarray       ,  _lowerCamelCase  : jnp.ndarray							):






       '''simple docstring'''



       raise NotImplementedError(
           F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called."""							)



class 							_UpperCamelCase (						A						):

 '''simple docstring'''







 @add_start_docstrings(lowercase_							)
 def __call__(  self  : Optional[int]       ,  _lowerCamelCase  : jnp.ndarray       ,  _lowerCamelCase  : jnp.ndarray       ,  _lowerCamelCase  : int       ,  **_lowerCamelCase  : Dict							):






       '''simple docstring'''



       for processor in self:
             __lowerCamelCase     :      int       						=						inspect.signature(processor.__call__							).parameters
             if len(lowercase_							) > 3:
                   if not all(arg in kwargs for arg in list(function_args.keys()							)[2:]							):
                         raise ValueError(
                             F"""Make sure that all the required parameters: {list(function_args.keys()							)} for """
                             F"""{processor.__class__} are passed to the logits processor."""							)
                   __lowerCamelCase     :      List[str]       						=						processor(lowercase_       ,  lowercase_       ,  lowercase_       ,  **lowercase_							)
             else:
                   __lowerCamelCase     :      Tuple       						=						processor(lowercase_       ,  lowercase_       ,  lowercase_							)
       return scores



class 							_UpperCamelCase (						A						):

 '''simple docstring'''







 def __init__(  self  : Union[str, Any]       ,  _lowerCamelCase  : float							):






       '''simple docstring'''



       if not isinstance(lowercase_       ,  lowercase_							) or not (temperature > 0):
             raise ValueError(F"""`temperature` has to be a strictly positive float, but is {temperature}"""							)

       __lowerCamelCase     :      str       						=						temperature


 def __call__(  self  : Any       ,  _lowerCamelCase  : jnp.ndarray       ,  _lowerCamelCase  : jnp.ndarray       ,  _lowerCamelCase  : int							):






       '''simple docstring'''



       __lowerCamelCase     :      Tuple       						=						scores / self.temperature
       return scores



class 							_UpperCamelCase (						A						):

 '''simple docstring'''







 def __init__(  self  : List[str]       ,  _lowerCamelCase  : float       ,  _lowerCamelCase  : float = -float("""Inf"""							)       ,  _lowerCamelCase  : int = 1							):






       '''simple docstring'''



       if not isinstance(lowercase_       ,  lowercase_							) or (top_p < 0 or top_p > 1.0):
             raise ValueError(F"""`top_p` has to be a float > 0 and < 1, but is {top_p}"""							)
       if not isinstance(lowercase_       ,  lowercase_							) or (min_tokens_to_keep < 1):
             raise ValueError(F"""`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}"""							)

       __lowerCamelCase     :      Any       						=						top_p
       __lowerCamelCase     :      Tuple       						=						filter_value
       __lowerCamelCase     :      str       						=						min_tokens_to_keep


 def __call__(  self  : Any       ,  _lowerCamelCase  : jnp.ndarray       ,  _lowerCamelCase  : jnp.ndarray       ,  _lowerCamelCase  : int							):






       '''simple docstring'''



       __lowerCamelCase						, __lowerCamelCase     :      Any       						=						lax.top_k(lowercase_       ,  scores.shape[-1]							)

       __lowerCamelCase     :      List[Any]       						=						jnp.full_like(lowercase_       ,  self.filter_value							)
       __lowerCamelCase     :      Dict       						=						jax.nn.softmax(lowercase_       ,  axis=-1							).cumsum(axis=-1							)
       __lowerCamelCase     :      Optional[int]       						=						cumulative_probs < self.top_p

       # include the token that is higher than top_p as well
       __lowerCamelCase     :      str       						=						jnp.roll(lowercase_       ,  1							)
       score_mask |= score_mask.at[:, 0].set(lowercase_							)

       # min tokens to keep
       __lowerCamelCase     :      Any       						=						score_mask.at[:, : self.min_tokens_to_keep].set(lowercase_							)

       __lowerCamelCase     :      str       						=						jnp.where(lowercase_       ,  lowercase_       ,  lowercase_							)
       __lowerCamelCase     :      Optional[int]       						=						jax.lax.sort_key_val(lowercase_       ,  lowercase_							)[-1]

       return next_scores



class 							_UpperCamelCase (						A						):

 '''simple docstring'''







 def __init__(  self  : List[str]       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : float = -float("""Inf"""							)       ,  _lowerCamelCase  : int = 1							):






       '''simple docstring'''



       if not isinstance(lowercase_       ,  lowercase_							) or top_k <= 0:
             raise ValueError(F"""`top_k` has to be a strictly positive integer, but is {top_k}"""							)

       __lowerCamelCase     :      str       						=						max(lowercase_       ,  lowercase_							)
       __lowerCamelCase     :      int       						=						filter_value


 def __call__(  self  : List[Any]       ,  _lowerCamelCase  : jnp.ndarray       ,  _lowerCamelCase  : jnp.ndarray       ,  _lowerCamelCase  : int							):






       '''simple docstring'''



       __lowerCamelCase						, __lowerCamelCase     :      List[Any]       						=						scores.shape
       __lowerCamelCase     :      str       						=						jnp.full(batch_size * vocab_size       ,  self.filter_value							)

       __lowerCamelCase     :      Optional[Any]       						=						min(self.top_k       ,  scores.shape[-1]							)  # Safety check
       __lowerCamelCase						, __lowerCamelCase     :      Optional[int]       						=						lax.top_k(lowercase_       ,  lowercase_							)
       __lowerCamelCase     :      List[Any]       						=						jnp.broadcast_to((jnp.arange(lowercase_							) * vocab_size)[:, None]       ,  (batch_size, topk)							).flatten()
       __lowerCamelCase     :      Optional[int]       						=						topk_scores.flatten()
       __lowerCamelCase     :      Tuple       						=						topk_indices.flatten() + shift

       __lowerCamelCase     :      str       						=						next_scores_flat.at[topk_indices_flat].set(lowercase_							)
       __lowerCamelCase     :      List[str]       						=						next_scores_flat.reshape(lowercase_       ,  lowercase_							)
       return next_scores



class 							_UpperCamelCase (						A						):

 '''simple docstring'''







 def __init__(  self  : int       ,  _lowerCamelCase  : int							):






       '''simple docstring'''



       __lowerCamelCase     :      List[str]       						=						bos_token_id


 def __call__(  self  : Union[str, Any]       ,  _lowerCamelCase  : jnp.ndarray       ,  _lowerCamelCase  : jnp.ndarray       ,  _lowerCamelCase  : int							):






       '''simple docstring'''



       __lowerCamelCase     :      Union[str, Any]       						=						jnp.full(scores.shape       ,  -float("""inf"""							)							)

       __lowerCamelCase     :      List[str]       						=						1 - jnp.bool_(cur_len - 1							)

       __lowerCamelCase     :      List[Any]       						=						jnp.where(lowercase_       ,  new_scores.at[:, self.bos_token_id].set(0							)       ,  lowercase_							)

       return scores



class 							_UpperCamelCase (						A						):

 '''simple docstring'''







 def __init__(  self  : Optional[Any]       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : int							):






       '''simple docstring'''



       __lowerCamelCase     :      Optional[int]       						=						max_length
       __lowerCamelCase     :      Optional[int]       						=						eos_token_id


 def __call__(  self  : str       ,  _lowerCamelCase  : jnp.ndarray       ,  _lowerCamelCase  : jnp.ndarray       ,  _lowerCamelCase  : int							):






       '''simple docstring'''



       __lowerCamelCase     :      Union[str, Any]       						=						jnp.full(scores.shape       ,  -float("""inf"""							)							)

       __lowerCamelCase     :      Optional[int]       						=						1 - jnp.bool_(cur_len - self.max_length + 1							)

       __lowerCamelCase     :      Optional[int]       						=						jnp.where(lowercase_       ,  new_scores.at[:, self.eos_token_id].set(0							)       ,  lowercase_							)

       return scores



class 							_UpperCamelCase (						A						):

 '''simple docstring'''







 def __init__(  self  : int       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : int							):






       '''simple docstring'''



       if not isinstance(lowercase_       ,  lowercase_							) or min_length < 0:
             raise ValueError(F"""`min_length` has to be a positive integer, but is {min_length}"""							)

       if not isinstance(lowercase_       ,  lowercase_							) or eos_token_id < 0:
             raise ValueError(F"""`eos_token_id` has to be a positive integer, but is {eos_token_id}"""							)

       __lowerCamelCase     :      Optional[int]       						=						min_length
       __lowerCamelCase     :      int       						=						eos_token_id


 def __call__(  self  : Tuple       ,  _lowerCamelCase  : jnp.ndarray       ,  _lowerCamelCase  : jnp.ndarray       ,  _lowerCamelCase  : int							):






       '''simple docstring'''



       __lowerCamelCase     :      Union[str, Any]       						=						1 - jnp.clip(cur_len - self.min_length       ,  0       ,  1							)

       __lowerCamelCase     :      str       						=						jnp.where(lowercase_       ,  scores.at[:, self.eos_token_id].set(-float("""inf"""							)							)       ,  lowercase_							)

       return scores



class 							_UpperCamelCase (						A						):

 '''simple docstring'''







 def __init__(  self  : Tuple       ,  _lowerCamelCase  : List[Any]       ,  _lowerCamelCase  : int							):






       '''simple docstring'''



       __lowerCamelCase     :      Tuple       						=						list(lowercase_							)
       __lowerCamelCase     :      int       						=						begin_index


 def __call__(  self  : Tuple       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : Dict       ,  _lowerCamelCase  : int							):






       '''simple docstring'''



       __lowerCamelCase     :      Union[str, Any]       						=						1 - jnp.bool_(cur_len - self.begin_index							)

       __lowerCamelCase     :      Optional[Any]       						=						jnp.where(lowercase_       ,  scores.at[:, self.begin_suppress_tokens].set(-float("""inf"""							)							)       ,  lowercase_							)

       return scores



class 							_UpperCamelCase (						A						):

 '''simple docstring'''







 def __init__(  self  : Union[str, Any]       ,  _lowerCamelCase  : list							):






       '''simple docstring'''



       __lowerCamelCase     :      Dict       						=						list(lowercase_							)


 def __call__(  self  : Union[str, Any]       ,  _lowerCamelCase  : jnp.ndarray       ,  _lowerCamelCase  : jnp.ndarray       ,  _lowerCamelCase  : int							):






       '''simple docstring'''



       __lowerCamelCase     :      str       						=						scores.at[..., self.suppress_tokens].set(-float("""inf"""							)							)

       return scores



class 							_UpperCamelCase (						A						):

 '''simple docstring'''







 def __init__(  self  : str       ,  _lowerCamelCase  : Union[str, Any]							):






       '''simple docstring'''



       __lowerCamelCase     :      int       						=						dict(lowercase_							)
       # Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the
       # index of the array corresponds to the index of the token to be forced, for XLA compatibility.
       # Indexes without forced tokens will have a negative value.
       __lowerCamelCase     :      Tuple       						=						jnp.ones((max(force_token_map.keys()							) + 1)       ,  dtype=jnp.intaa							) * -1
       for index, token in force_token_map.items():
             if token is not None:
                   __lowerCamelCase     :      Dict       						=						force_token_array.at[index].set(lowercase_							)
       __lowerCamelCase     :      int       						=						jnp.intaa(lowercase_							)


 def __call__(  self  : Tuple       ,  _lowerCamelCase  : jnp.ndarray       ,  _lowerCamelCase  : jnp.ndarray       ,  _lowerCamelCase  : int							):






       '''simple docstring'''



       def _force_token(_lowerCamelCase  : Optional[Any]							):
             __lowerCamelCase     :      List[str]       						=						scores.shape[0]
             __lowerCamelCase     :      Union[str, Any]       						=						self.force_token_array[generation_idx]

             __lowerCamelCase     :      str       						=						jnp.ones_like(lowercase_       ,  dtype=scores.dtype							) * -float("""inf"""							)
             __lowerCamelCase     :      Optional[int]       						=						jnp.zeros((batch_size, 1)       ,  dtype=scores.dtype							)
             __lowerCamelCase     :      Optional[int]       						=						lax.dynamic_update_slice(lowercase_       ,  lowercase_       ,  (0, current_token)							)
             return new_scores

       __lowerCamelCase     :      List[str]       						=						lax.cond(
           cur_len >= self.force_token_array.shape[0]       ,  lambda: scores       ,  lambda: lax.cond(
               self.force_token_array[cur_len] >= 0       ,  lambda: _force_token(lowercase_							)       ,  lambda: scores       ,  )       ,  )
       return scores



class 							_UpperCamelCase (						A						):

 '''simple docstring'''







 def __init__(  self  : List[str]       ,  _lowerCamelCase  : Optional[Any]       ,  _lowerCamelCase  : Optional[int]       ,  _lowerCamelCase  : List[Any]							):






       '''simple docstring'''



       __lowerCamelCase     :      Any       						=						generate_config.eos_token_id
       __lowerCamelCase     :      Dict       						=						generate_config.no_timestamps_token_id
       __lowerCamelCase     :      Optional[int]       						=						generate_config.no_timestamps_token_id + 1

       __lowerCamelCase     :      Any       						=						decoder_input_length + 1

       if generate_config.is_multilingual:
             # room for language token and task token
             self.begin_index += 2
       if hasattr(lowercase_       ,  """max_initial_timestamp_index"""							):
             __lowerCamelCase     :      List[Any]       						=						generate_config.max_initial_timestamp_index
       else:
             __lowerCamelCase     :      Tuple       						=						model_config.vocab_size
       if self.max_initial_timestamp_index is None:
             __lowerCamelCase     :      Optional[Any]       						=						model_config.vocab_size


 def __call__(  self  : int       ,  _lowerCamelCase  : List[str]       ,  _lowerCamelCase  : List[Any]       ,  _lowerCamelCase  : Optional[Any]							):






       '''simple docstring'''



       __lowerCamelCase     :      int       						=						scores.at[:, self.no_timestamps_token_id].set(-float("""inf"""							)							)

       def handle_pairs(_lowerCamelCase  : Optional[Any]       ,  _lowerCamelCase  : int							):
             __lowerCamelCase     :      Union[str, Any]       						=						jnp.where((cur_len - self.begin_index) >= 1       ,  lowercase_       ,  lowercase_							)
             __lowerCamelCase     :      Union[str, Any]       						=						jnp.where(
                 input_ids_k[cur_len - 1] >= self.timestamp_begin       ,  True and last_was_timestamp       ,  lowercase_       ,  )

             __lowerCamelCase     :      Optional[Any]       						=						jnp.where((cur_len - self.begin_index) < 2       ,  lowercase_       ,  lowercase_							)
             __lowerCamelCase     :      List[str]       						=						jnp.where(
                 input_ids_k[cur_len - 2] >= self.timestamp_begin       ,  lowercase_       ,  lowercase_       ,  )

             return jnp.where(
                 lowercase_       ,  jnp.where(
                     penultimate_was_timestamp > 0       ,  scores_k.at[self.timestamp_begin :].set(-float("""inf"""							)							)       ,  scores_k.at[: self.eos_token_id].set(-float("""inf"""							)							)       ,  )       ,  lowercase_       ,  )

       __lowerCamelCase     :      Any       						=						jax.vmap(lowercase_							)(lowercase_       ,  lowercase_							)

       __lowerCamelCase     :      Dict       						=						jnp.where(cur_len == self.begin_index       ,  lowercase_       ,  lowercase_							)
       __lowerCamelCase     :      Dict       						=						jnp.where(
           self.max_initial_timestamp_index is not None       ,  True and apply_max_initial_timestamp       ,  lowercase_       ,  )

       __lowerCamelCase     :      Optional[int]       						=						self.timestamp_begin + self.max_initial_timestamp_index

       __lowerCamelCase     :      str       						=						jnp.where(
           lowercase_       ,  scores.at[:, last_allowed + 1 :].set(-float("""inf"""							)							)       ,  lowercase_       ,  )

       # if sum of probability over timestamps is above any other token, sample timestamp
       __lowerCamelCase     :      str       						=						jax.nn.log_softmax(lowercase_       ,  axis=-1							)

       def handle_cumulative_probs(_lowerCamelCase  : int       ,  _lowerCamelCase  : List[str]							):
             __lowerCamelCase     :      Union[str, Any]       						=						jax.nn.logsumexp(logprobs_k[self.timestamp_begin :]       ,  axis=-1							)
             __lowerCamelCase     :      List[Any]       						=						jnp.max(logprobs_k[: self.timestamp_begin]							)
             return jnp.where(
                 timestamp_logprob > max_text_token_logprob       ,  scores_k.at[: self.timestamp_begin].set(-float("""inf"""							)							)       ,  lowercase_       ,  )

       __lowerCamelCase     :      str       						=						jax.vmap(lowercase_							)(lowercase_       ,  lowercase_							)

       return scores







# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


__UpperCamelCase    :						Any     =							{
    'configuration_mgp_str': ['MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MgpstrConfig'],
    'processing_mgp_str': ['MgpstrProcessor'],
    'tokenization_mgp_str': ['MgpstrTokenizer'],
}

try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    __UpperCamelCase    :						Tuple     =							[
        'MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST',
        'MgpstrModel',
        'MgpstrPreTrainedModel',
        'MgpstrForSceneTextRecognition',
    ]

if TYPE_CHECKING:
    from .configuration_mgp_str import MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP, MgpstrConfig
    from .processing_mgp_str import MgpstrProcessor
    from .tokenization_mgp_str import MgpstrTokenizer

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_mgp_str import (
            MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST,
            MgpstrForSceneTextRecognition,
            MgpstrModel,
            MgpstrPreTrainedModel,
        )
else:
    import sys

    __UpperCamelCase    :						Optional[Any]     =							_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)



