

'''simple docstring'''







import enum
import warnings

from ..tokenization_utils import TruncationStrategy
from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
      import tensorflow as tf

      from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING

if is_torch_available():
      from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING

__lowerCamelCase		       =    logging.get_logger(__name__)


class 					A__      (      enum.Enum			):
    lowercase						=		0
    lowercase						=		1


@add_end_docstrings(_snake_case			)
class 					A__      (      _snake_case			):
    lowercase						=		"generated"



    def __init__(					self		,				*UpperCamelCase__		,				**UpperCamelCase__       )						->      Optional[Any]:





           '''simple docstring'''
           super().__init__(*UpperCamelCase__		,				**UpperCamelCase__       )

           self.check_model_type(
               TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
               if self.framework == """tf"""
               else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING       )



    def 					snake_case_			(					self		,				UpperCamelCase__=None		,				UpperCamelCase__=None		,				UpperCamelCase__=None		,				UpperCamelCase__=None		,				UpperCamelCase__=None		,				UpperCamelCase__=None		,				**UpperCamelCase__		,				)						->      Union[str, Any]:





           '''simple docstring'''
           A_						=      {}
           if truncation is not None:
                  A_						=      truncation

           A_						=      generate_kwargs

           A_						=      {}
           if return_tensors is not None and return_type is None:
                  A_						=      ReturnType.TENSORS if return_tensors else ReturnType.TEXT
           if return_type is not None:
                  A_						=      return_type

           if clean_up_tokenization_spaces is not None:
                  A_						=      clean_up_tokenization_spaces

           if stop_sequence is not None:
                  A_						=      self.tokenizer.encode(UpperCamelCase__		,				add_special_tokens=UpperCamelCase__       )
                  if len(UpperCamelCase__       ) > 1:
                         warnings.warn(
                             """Stopping on a multiple token sequence is not yet supported on transformers. The first token of"""
                             """ the stop sequence will be used as the stop sequence string in the interim."""       )
                  A_						=      stop_sequence_ids[0]

           return preprocess_params, forward_params, postprocess_params



    def 					snake_case_			(					self		,				UpperCamelCase__		,				UpperCamelCase__		,				UpperCamelCase__       )						->      Dict:





           '''simple docstring'''
           return True



    def 					snake_case_			(					self		,				*UpperCamelCase__		,				UpperCamelCase__       )						->      Optional[int]:





           '''simple docstring'''
           A_						=      self.model.config.prefix if self.model.config.prefix is not None else """"""
           if isinstance(args[0]		,				UpperCamelCase__       ):
                  if self.tokenizer.pad_token_id is None:
                         raise ValueError("""Please make sure that the tokenizer has a pad_token_id when using a batch input"""       )
                  A_						=      ([prefix + arg for arg in args[0]],)
                  A_						=      True

           elif isinstance(args[0]		,				UpperCamelCase__       ):
                  A_						=      (prefix + args[0],)
                  A_						=      False
           else:
                  raise ValueError(
                      f''' `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`'''       )
           A_						=      self.tokenizer(*UpperCamelCase__		,				padding=UpperCamelCase__		,				truncation=UpperCamelCase__		,				return_tensors=self.framework       )
           # This is produced by tokenizers but is an invalid generate kwargs
           if "token_type_ids" in inputs:
                  del inputs["token_type_ids"]
           return inputs



    def __call__(					self		,				*UpperCamelCase__		,				**UpperCamelCase__       )						->      int:





           '''simple docstring'''
           A_						=      super().__call__(*UpperCamelCase__		,				**UpperCamelCase__       )
           if (
               isinstance(args[0]		,				UpperCamelCase__       )
               and all(isinstance(UpperCamelCase__		,				UpperCamelCase__       ) for el in args[0]       )
               and all(len(UpperCamelCase__       ) == 1 for res in result       )
           ):
                  return [res[0] for res in result]
           return result



    def 					snake_case_			(					self		,				UpperCamelCase__		,				UpperCamelCase__=TruncationStrategy.DO_NOT_TRUNCATE		,				**UpperCamelCase__       )						->      Dict:





           '''simple docstring'''
           A_						=      self._parse_and_tokenize(UpperCamelCase__		,				truncation=UpperCamelCase__		,				**UpperCamelCase__       )
           return inputs



    def 					snake_case_			(					self		,				UpperCamelCase__		,				**UpperCamelCase__       )						->      int:





           '''simple docstring'''
           if self.framework == "pt":
                  A_					,			A_						=      model_inputs["""input_ids"""].shape
           elif self.framework == "tf":
                  A_					,			A_						=      tf.shape(model_inputs["""input_ids"""]       ).numpy()

           A_						=      generate_kwargs.get("""min_length"""		,				self.model.config.min_length       )
           A_						=      generate_kwargs.get("""max_length"""		,				self.model.config.max_length       )
           self.check_inputs(UpperCamelCase__		,				generate_kwargs["""min_length"""]		,				generate_kwargs["""max_length"""]       )
           A_						=      self.model.generate(**UpperCamelCase__		,				**UpperCamelCase__       )
           A_						=      output_ids.shape[0]
           if self.framework == "pt":
                  A_						=      output_ids.reshape(UpperCamelCase__		,				out_b // in_b		,				*output_ids.shape[1:]       )
           elif self.framework == "tf":
                  A_						=      tf.reshape(UpperCamelCase__		,				(in_b, out_b // in_b, *output_ids.shape[1:])       )
           return {"output_ids": output_ids}







    def 					snake_case_			(					self		,				UpperCamelCase__		,				UpperCamelCase__=ReturnType.TEXT		,				UpperCamelCase__=False       )						->      Optional[int]:





           '''simple docstring'''
           A_						=      []
           for output_ids in model_outputs["output_ids"][0]:
                  if return_type == ReturnType.TENSORS:
                         A_						=      {f'''{self.return_name}_token_ids''': output_ids}
                  elif return_type == ReturnType.TEXT:
                         A_						=      {
                             f'''{self.return_name}_text''': self.tokenizer.decode(
                                 UpperCamelCase__		,				skip_special_tokens=UpperCamelCase__		,				clean_up_tokenization_spaces=UpperCamelCase__		,				)
                         }
                  records.append(UpperCamelCase__       )
           return records


@add_end_docstrings(_snake_case			)
class 					A__      (      _snake_case			):
    lowercase						=		"summary"



    def __call__(					self		,				*UpperCamelCase__		,				**UpperCamelCase__       )						->      Optional[Any]:





           '''simple docstring'''
           return super().__call__(*UpperCamelCase__		,				**UpperCamelCase__       )







    def 					snake_case_			(					self		,				UpperCamelCase__		,				UpperCamelCase__		,				UpperCamelCase__       )						->      bool:





           '''simple docstring'''
           if max_length < min_length:
                  logger.warning(f'''Your min_length={min_length} must be inferior than your max_length={max_length}.'''       )

           if input_length < max_length:
                  logger.warning(
                      f'''Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is '''
                      """a summarization task, where outputs shorter than the input are typically wanted, you might """
                      f'''consider decreasing max_length manually, e.g. summarizer(\'...\', max_length={input_length//2})'''       )


@add_end_docstrings(_snake_case			)
class 					A__      (      _snake_case			):
    lowercase						=		"translation"



    def 					snake_case_			(					self		,				UpperCamelCase__		,				UpperCamelCase__		,				UpperCamelCase__       )						->      int:





           '''simple docstring'''
           if input_length > 0.9 * max_length:
                  logger.warning(
                      f'''Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider '''
                      """increasing your max_length manually, e.g. translator('...', max_length=400)"""       )
           return True



    def 					snake_case_			(					self		,				*UpperCamelCase__		,				UpperCamelCase__=TruncationStrategy.DO_NOT_TRUNCATE		,				UpperCamelCase__=None		,				UpperCamelCase__=None       )						->      int:





           '''simple docstring'''
           if getattr(self.tokenizer		,				"""_build_translation_inputs"""		,				UpperCamelCase__       ):
                  return self.tokenizer._build_translation_inputs(
                      *UpperCamelCase__		,				return_tensors=self.framework		,				truncation=UpperCamelCase__		,				src_lang=UpperCamelCase__		,				tgt_lang=UpperCamelCase__       )
           else:
                  return super()._parse_and_tokenize(*UpperCamelCase__		,				truncation=UpperCamelCase__       )



    def 					snake_case_			(					self		,				UpperCamelCase__=None		,				UpperCamelCase__=None		,				**UpperCamelCase__       )						->      Any:





           '''simple docstring'''
           A_					,			A_					,			A_						=      super()._sanitize_parameters(**UpperCamelCase__       )
           if src_lang is not None:
                  A_						=      src_lang
           if tgt_lang is not None:
                  A_						=      tgt_lang
           if src_lang is None and tgt_lang is None:
                  # Backward compatibility, direct arguments use is preferred.
                  A_						=      kwargs.get("""task"""		,				self.task       )
                  A_						=      task.split("""_"""       )
                  if task and len(UpperCamelCase__       ) == 4:
                         # translation, XX, to YY
                         A_						=      items[1]
                         A_						=      items[3]
           return preprocess_params, forward_params, postprocess_params







    def __call__(					self		,				*UpperCamelCase__		,				**UpperCamelCase__       )						->      Dict:





           '''simple docstring'''
           return super().__call__(*UpperCamelCase__		,				**UpperCamelCase__       )



'''simple docstring'''







__lowerCamelCase		       =    range(2, 20 + 1)
__lowerCamelCase		       =    [10**k for k in range(ks[-1] + 1)]
__lowerCamelCase		       =    {}
def       UpperCAmelCase__    (      UpperCAmelCase__,       UpperCAmelCase__,       UpperCAmelCase__,       UpperCAmelCase__				)			->			Tuple:
       A_						=      sum(a_i[j] for j in range(UpperCAmelCase__,       len(UpperCAmelCase__				)				)				)
       A_						=      sum(a_i[j] * base[j] for j in range(min(len(UpperCAmelCase__				),       UpperCAmelCase__				)				)				)

       A_					,			A_						=      0, 0
       A_						=      n - i

       A_						=      memo.get(UpperCAmelCase__				)

       if sub_memo is not None:
              A_						=      sub_memo.get(UpperCAmelCase__				)

              if jumps is not None and len(UpperCAmelCase__				) > 0:
                     # find and make the largest jump without going over
                     A_						=      -1
                     for _k in range(len(UpperCAmelCase__				) - 1,       -1,       -1				):
                            if jumps[_k][2] <= k and jumps[_k][1] <= max_dn:
                                   A_						=      _k
                                   break

                     if max_jump >= 0:
                            A_					,			A_					,			A_						=      jumps[max_jump]
                            # since the difference between jumps is cached, add c
                            A_						=      diff + c
                            for j in range(min(UpperCAmelCase__,       len(UpperCAmelCase__				)				)				):
                                   A_					,			A_						=      divmod(UpperCAmelCase__,       10				)
                            if new_c > 0:
                                   add(UpperCAmelCase__,       UpperCAmelCase__,       UpperCAmelCase__				)

              else:
                     A_						=      []
       else:
              A_						=      {c: []}
              A_						=      sub_memo

       if dn >= max_dn or c + diff >= base[k]:
              return diff, dn

       if k > ks[0]:
              while True:
                     # keep doing smaller jumps
                     A_					,			A_						=      next_term(UpperCAmelCase__,       k - 1,       i + dn,       UpperCAmelCase__				)
                     diff += _diff
                     dn += terms_jumped

                     if dn >= max_dn or c + diff >= base[k]:
                            break
       else:
              # would be too small a jump, just compute sequential terms instead
              A_					,			A_						=      compute(UpperCAmelCase__,       UpperCAmelCase__,       i + dn,       UpperCAmelCase__				)
              diff += _diff
              dn += terms_jumped

       A_						=      sub_memo[c]

       # keep jumps sorted by # of terms skipped
       A_						=      0
       while j < len(UpperCAmelCase__				):
              if jumps[j][1] > dn:
                     break
              j += 1

       # cache the jump for this value digitsum(b) and c
       sub_memo[c].insert(UpperCAmelCase__,       (diff, dn, k)				)
       return (diff, dn)
def       UpperCAmelCase__    (      UpperCAmelCase__,       UpperCAmelCase__,       UpperCAmelCase__,       UpperCAmelCase__				)			->			int:
       if i >= n:
              return 0, i
       if k > len(UpperCAmelCase__				):
              a_i.extend([0 for _ in range(k - len(UpperCAmelCase__				)				)]				)

       # note: a_i -> b * 10^k + c
       # ds_b -> digitsum(b)
       # ds_c -> digitsum(c)
       A_						=      i
       A_					,			A_					,			A_						=      0, 0, 0
       for j in range(len(UpperCAmelCase__				)				):
              if j >= k:
                     ds_b += a_i[j]
              else:
                     ds_c += a_i[j]

       while i < n:
              i += 1
              A_						=      ds_c + ds_b
              diff += addend
              A_						=      0
              for j in range(UpperCAmelCase__				):
                     A_						=      a_i[j] + addend
                     A_					,			A_						=      divmod(UpperCAmelCase__,       10				)

                     ds_c += a_i[j]

              if addend > 0:
                     break

       if addend > 0:
              add(UpperCAmelCase__,       UpperCAmelCase__,       UpperCAmelCase__				)
       return diff, i - start_i
def       UpperCAmelCase__    (      UpperCAmelCase__,       UpperCAmelCase__,       UpperCAmelCase__				)			->			str:
       for j in range(UpperCAmelCase__,       len(UpperCAmelCase__				)				):
              A_						=      digits[j] + addend
              if s >= 10:
                     A_					,			A_						=      divmod(UpperCAmelCase__,       10				)
                     A_						=      addend // 10 + quotient
              else:
                     A_						=      s
                     A_						=      addend // 10

              if addend == 0:
                     break

       while addend > 0:
              A_					,			A_						=      divmod(UpperCAmelCase__,       10				)
              digits.append(UpperCAmelCase__				)
def       UpperCAmelCase__    (      UpperCAmelCase__ = 10**15				)			->			int:
       A_						=      [1]
       A_						=      1
       A_						=      0
       while True:
              A_					,			A_						=      next_term(UpperCAmelCase__,       20,       i + dn,       UpperCAmelCase__				)
              dn += terms_jumped
              if dn == n - i:
                     break

       A_						=      0
       for j in range(len(UpperCAmelCase__				)				):
              a_n += digits[j] * 10**j
       return a_n


if __name__ == "__main__":
      print(f"""{solution() = }""")
