

import argparse
import inspect
import logging
from typing import Tuple

import numpy as np
import torch

from transformers import (
    AutoTokenizer,
    BloomForCausalLM,
    BloomTokenizerFast,
    CTRLLMHeadModel,
    CTRLTokenizer,
    GenerationMixin,
    GPTaLMHeadModel,
    GPTaTokenizer,
    GPTJForCausalLM,
    LlamaForCausalLM,
    LlamaTokenizer,
    OpenAIGPTLMHeadModel,
    OpenAIGPTTokenizer,
    OPTForCausalLM,
    TransfoXLLMHeadModel,
    TransfoXLTokenizer,
    XLMTokenizer,
    XLMWithLMHeadModel,
    XLNetLMHeadModel,
    XLNetTokenizer,
)
from transformers.modeling_outputs import CausalLMOutputWithPast


logging.basicConfig(
    format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''',
    datefmt='''%m/%d/%Y %H:%M:%S''',
    level=logging.INFO,
)
_a 	=       logging.getLogger(__name__)

_a 	=       int(1_0_0_0_0)  # Hardcoded max length to avoid infinite loop

_a 	=       {
    '''gpt2''': (GPTaLMHeadModel, GPTaTokenizer),
    '''ctrl''': (CTRLLMHeadModel, CTRLTokenizer),
    '''openai-gpt''': (OpenAIGPTLMHeadModel, OpenAIGPTTokenizer),
    '''xlnet''': (XLNetLMHeadModel, XLNetTokenizer),
    '''transfo-xl''': (TransfoXLLMHeadModel, TransfoXLTokenizer),
    '''xlm''': (XLMWithLMHeadModel, XLMTokenizer),
    '''gptj''': (GPTJForCausalLM, AutoTokenizer),
    '''bloom''': (BloomForCausalLM, BloomTokenizerFast),
    '''llama''': (LlamaForCausalLM, LlamaTokenizer),
    '''opt''': (OPTForCausalLM, GPTaTokenizer),
}

# Padding text to help Transformer-XL and XLNet with short prompts as proposed by Aman Rusia
# in https://github.com/rusiaaman/XLNet-gen#methodology
# and https://medium.com/@amanrusia/xlnet-speaks-comparison-to-gpt-2-ea1a4e9ba39e
_a 	=       '''In 1991, the remains of Russian Tsar Nicholas II and his family
(except for Alexei and Maria) are discovered.
The voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the
remainder of the story. 1883 Western Siberia,
a young Grigori Rasputin is asked by his father and a group of men to perform magic.
Rasputin has a vision and denounces one of the men as a horse thief. Although his
father initially slaps him for making such an accusation, Rasputin watches as the
man is chased outside and beaten. Twenty years later, Rasputin sees a vision of
the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous,
with people, even a bishop, begging for his blessing. <eod> </s> <eos>'''







def _a			(	SCREAMING_SNAKE_CASE		:      Dict		)   ->   List[str]:

 """simple docstring"""






 np.random.seed(args.seed		)
 torch.manual_seed(args.seed		)
 if args.n_gpu > 0:
  torch.cuda.manual_seed_all(args.seed		)







def _a			(	SCREAMING_SNAKE_CASE		:      Tuple   , SCREAMING_SNAKE_CASE		:      List[str]   , SCREAMING_SNAKE_CASE		:      List[Any]   , SCREAMING_SNAKE_CASE		:      Optional[int]		)   ->   Dict:

 """simple docstring"""






 if args.temperature > 0.7:
  logger.info('CTRL typically works better with lower temperatures (and lower top_k).'		)

 __lowerCAmelCase:       List[Any]            =				tokenizer.encode(SCREAMING_SNAKE_CASE   , add_special_tokens=SCREAMING_SNAKE_CASE		)
 if not any(encoded_prompt[0] == x for x in tokenizer.control_codes.values()		):
  logger.info('WARNING! You are not starting your generation from a control code so you won\'t get good results'		)
 return prompt_text







def _a			(	SCREAMING_SNAKE_CASE		:      str   , SCREAMING_SNAKE_CASE		:      Optional[Any]   , SCREAMING_SNAKE_CASE		:      Tuple   , SCREAMING_SNAKE_CASE		:      int		)   ->   Optional[int]:

 """simple docstring"""






 __lowerCAmelCase:       Optional[int]            =				hasattr(model.config   , 'use_lang_emb'		) and model.config.use_lang_emb
 if hasattr(model.config   , 'lang2id'		) and use_lang_emb:
  __lowerCAmelCase:       Tuple            =				model.config.langaid.keys()
  if args.xlm_language in available_languages:
   __lowerCAmelCase:       Any            =				args.xlm_language
  else:
   __lowerCAmelCase:       Any            =				None
   while language not in available_languages:
    __lowerCAmelCase:       Optional[Any]            =				input('Using XLM. Select language in ' + str(list(SCREAMING_SNAKE_CASE		)		) + ' >>> '		)

  __lowerCAmelCase:       Dict            =				model.config.langaid[language]
  # kwargs["language"] = tokenizer.lang2id[language]

 # TODO fix mask_token_id setup when configurations will be synchronized between models and tokenizers
 # XLM masked-language modeling (MLM) models need masked token
 # is_xlm_mlm = "mlm" in args.model_name_or_path
 # if is_xlm_mlm:
 #     kwargs["mask_token_id"] = tokenizer.mask_token_id

 return prompt_text







def _a			(	SCREAMING_SNAKE_CASE		:      str   , SCREAMING_SNAKE_CASE		:      Tuple   , SCREAMING_SNAKE_CASE		:      Optional[int]   , SCREAMING_SNAKE_CASE		:      Any		)   ->   Optional[Any]:

 """simple docstring"""






 __lowerCAmelCase:       Any            =				args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
 __lowerCAmelCase:       Union[str, Any]            =				prefix + prompt_text
 return prompt_text







def _a			(	SCREAMING_SNAKE_CASE		:      str   , SCREAMING_SNAKE_CASE		:      Dict   , SCREAMING_SNAKE_CASE		:      int   , SCREAMING_SNAKE_CASE		:      Optional[Any]		)   ->   Union[str, Any]:

 """simple docstring"""






 __lowerCAmelCase:       Optional[int]            =				args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
 __lowerCAmelCase:       List[Any]            =				prefix + prompt_text
 return prompt_text


_a 	=       {
    '''ctrl''': prepare_ctrl_input,
    '''xlm''': prepare_xlm_input,
    '''xlnet''': prepare_xlnet_input,
    '''transfo-xl''': prepare_transfoxl_input,
}







def _a			(	SCREAMING_SNAKE_CASE		:      Optional[Any]   , SCREAMING_SNAKE_CASE		:      Tuple		)   ->   Union[str, Any]:

 """simple docstring"""






 if length < 0 and max_sequence_length > 0:
  __lowerCAmelCase:       Optional[int]            =				max_sequence_length
 elif 0 < max_sequence_length < length:
  __lowerCAmelCase:       Union[str, Any]            =				max_sequence_length  # No generation bigger than model size
 elif length < 0:
  __lowerCAmelCase:       List[str]            =				MAX_LENGTH  # avoid infinite loop
 return length







def _a			(	SCREAMING_SNAKE_CASE		:      str		)   ->   str:

 """simple docstring"""






 __lowerCAmelCase:       Optional[Any]            =				None
 if hasattr(SCREAMING_SNAKE_CASE   , 'hidden_size'		):
  __lowerCAmelCase:       Union[str, Any]            =				model_config.hidden_size
 elif hasattr(SCREAMING_SNAKE_CASE   , 'n_embed'		):
  __lowerCAmelCase:       List[str]            =				model_config.n_embed
 elif hasattr(SCREAMING_SNAKE_CASE   , 'n_embd'		):
  __lowerCAmelCase:       Tuple            =				model_config.n_embd

 __lowerCAmelCase:       str            =				None
 if hasattr(SCREAMING_SNAKE_CASE   , 'num_attention_heads'		):
  __lowerCAmelCase:       Optional[int]            =				model_config.num_attention_heads
 elif hasattr(SCREAMING_SNAKE_CASE   , 'n_head'		):
  __lowerCAmelCase:       str            =				model_config.n_head

 if embedding_size is None or num_head is None or num_head == 0:
  raise ValueError('Check the model config'		)

 __lowerCAmelCase:       Tuple            =				int(embedding_size / num_head		)
 if hasattr(SCREAMING_SNAKE_CASE   , 'n_layer'		):
  __lowerCAmelCase:       List[Any]            =				model_config.n_layer
 elif hasattr(SCREAMING_SNAKE_CASE   , 'num_hidden_layers'		):
  __lowerCAmelCase:       Optional[Any]            =				model_config.num_hidden_layers
 else:
  raise ValueError('Number of hidden layers couldn\'t be determined from the model config'		)

 return num_layer, num_head, num_embedding_size_per_head







def _a			(	SCREAMING_SNAKE_CASE		:      Optional[Any]   , SCREAMING_SNAKE_CASE		:      Tuple   , SCREAMING_SNAKE_CASE		:      int		)   ->   List[str]:

 """simple docstring"""






 __lowerCAmelCase:       List[str]            =				sparse_model_config(model.config		)
 if model.config.model_type == "bloom":
  __lowerCAmelCase:       Dict            =				tuple(
      (
          torch.empty(int(num_attention_heads * batch_size		)   , SCREAMING_SNAKE_CASE   , SCREAMING_SNAKE_CASE		)
          .to(model.dtype		)
          .to(model.device		),
          torch.empty(int(num_attention_heads * batch_size		)   , SCREAMING_SNAKE_CASE   , SCREAMING_SNAKE_CASE		)
          .to(model.dtype		)
          .to(model.device		),
      )
      for _ in range(SCREAMING_SNAKE_CASE		)		)
 else:
  __lowerCAmelCase:       Tuple            =				tuple(
      (
          torch.empty(SCREAMING_SNAKE_CASE   , SCREAMING_SNAKE_CASE   , SCREAMING_SNAKE_CASE   , SCREAMING_SNAKE_CASE		)
          .to(model.dtype		)
          .to(model.device		),
          torch.empty(SCREAMING_SNAKE_CASE   , SCREAMING_SNAKE_CASE   , SCREAMING_SNAKE_CASE   , SCREAMING_SNAKE_CASE		)
          .to(model.dtype		)
          .to(model.device		),
      )
      for _ in range(SCREAMING_SNAKE_CASE		)		)
 return past_key_values







def _a			(	SCREAMING_SNAKE_CASE		:      Optional[Any]   , SCREAMING_SNAKE_CASE		:      Optional[int]   , SCREAMING_SNAKE_CASE		:      str		)   ->   Optional[int]:

 """simple docstring"""






 __lowerCAmelCase:       Union[str, Any]            =				len(SCREAMING_SNAKE_CASE		)
 __lowerCAmelCase:       Union[str, Any]            =				tokenizer.batch_encode_plus(SCREAMING_SNAKE_CASE   , return_tensors='pt'		)
 __lowerCAmelCase:       List[str]            =				dummy_input.to(model.device		)
 if model.config.use_cache:
  __lowerCAmelCase:       List[str]            =				generate_past_key_values(SCREAMING_SNAKE_CASE   , SCREAMING_SNAKE_CASE   , 1		)
 __lowerCAmelCase:       Optional[int]            =				torch.cat(
     [
         torch.zeros(dummy_input['attention_mask'].shape[0]   , 1		)
         .to(dummy_input['attention_mask'].dtype		)
         .to(model.device		),
         dummy_input['attention_mask'],
     ]   , -1   , )
 return dummy_input






class 							A_			(		snake_case__ ):
     _lowercase      :					Optional[Any]       =     ('_optimized', '_default')


     def __init__(							self      :		Tuple      ,  UpperCAmelCase      :		Tuple      ,  UpperCAmelCase      :		int )							->     Dict:
      __lowerCAmelCase:       Optional[Any]            =				optimized
      __lowerCAmelCase:       Dict            =				default


     def __call__(							self      :		List[Any]      ,  *UpperCAmelCase      :		Optional[Any]      ,  **UpperCAmelCase      :		str )							->     Tuple:
      if kwargs["past_key_values"] is None and self._default.config.use_cache:
       __lowerCAmelCase:       Any            =				generate_past_key_values(self._default      ,  kwargs['input_ids'].shape[0]      ,  0 )
      kwargs.pop('position_ids'      ,  UpperCAmelCase )
      for k in list(kwargs.keys() ):
       if kwargs[k] is None or isinstance(kwargs[k]      ,  UpperCAmelCase ):
        kwargs.pop(UpperCAmelCase )
      __lowerCAmelCase:       Optional[Any]            =				self._optimized(**UpperCAmelCase )
      __lowerCAmelCase:       str            =				outputs[0]
      __lowerCAmelCase:       Dict            =				outputs[1]
      __lowerCAmelCase:       List[str]            =				CausalLMOutputWithPast(
          loss=UpperCAmelCase      ,  logits=UpperCAmelCase      ,  past_key_values=UpperCAmelCase      ,  hidden_states=UpperCAmelCase      ,  attentions=UpperCAmelCase      ,  )
      return fixed_output


     def __getattr__(							self      :		List[Any]      ,  UpperCAmelCase      :		int )							->     Any:
      return getattr(self._default      ,  UpperCAmelCase )


     def   UpperCAmelCase  (							self      :		Tuple      ,  UpperCAmelCase      :		str      ,  UpperCAmelCase      :		List[str]=None      ,  UpperCAmelCase      :		Dict=None      ,  UpperCAmelCase      :		str=None      ,  **UpperCAmelCase      :		List[str] )							->     Tuple:
      return self._default.prepare_inputs_for_generation(
          UpperCAmelCase      ,  past_key_values=UpperCAmelCase      ,  inputs_embeds=UpperCAmelCase      ,  use_cache=UpperCAmelCase      ,  **UpperCAmelCase )


     def   UpperCAmelCase  (							self      :		List[Any]      ,  UpperCAmelCase      :		Tuple[Tuple[torch.Tensor]]      ,  UpperCAmelCase      :		torch.Tensor )							->     Tuple[Tuple[torch.Tensor]]:
      return self._default._reorder_cache(UpperCAmelCase      ,  UpperCAmelCase )







def _a			(	)   ->   Dict:

 """simple docstring"""






 __lowerCAmelCase:       Optional[int]            =				argparse.ArgumentParser()
 parser.add_argument(
     '--model_type'   , default=SCREAMING_SNAKE_CASE   , type=SCREAMING_SNAKE_CASE   , required=SCREAMING_SNAKE_CASE   , help='Model type selected in the list: ' + ', '.join(MODEL_CLASSES.keys()		)   , )
 parser.add_argument(
     '--model_name_or_path'   , default=SCREAMING_SNAKE_CASE   , type=SCREAMING_SNAKE_CASE   , required=SCREAMING_SNAKE_CASE   , help='Path to pre-trained model or shortcut name selected in the list: ' + ', '.join(MODEL_CLASSES.keys()		)   , )

 parser.add_argument('--prompt'   , type=SCREAMING_SNAKE_CASE   , default=''		)
 parser.add_argument('--length'   , type=SCREAMING_SNAKE_CASE   , default=20		)
 parser.add_argument('--stop_token'   , type=SCREAMING_SNAKE_CASE   , default=SCREAMING_SNAKE_CASE   , help='Token at which text generation is stopped'		)

 parser.add_argument(
     '--temperature'   , type=SCREAMING_SNAKE_CASE   , default=1.0   , help='temperature of 1.0 has no effect, lower tend toward greedy sampling'   , )
 parser.add_argument(
     '--repetition_penalty'   , type=SCREAMING_SNAKE_CASE   , default=1.0   , help='primarily useful for CTRL model; in that case, use 1.2'		)
 parser.add_argument('--k'   , type=SCREAMING_SNAKE_CASE   , default=0		)
 parser.add_argument('--p'   , type=SCREAMING_SNAKE_CASE   , default=0.9		)

 parser.add_argument('--prefix'   , type=SCREAMING_SNAKE_CASE   , default=''   , help='Text added prior to input.'		)
 parser.add_argument('--padding_text'   , type=SCREAMING_SNAKE_CASE   , default=''   , help='Deprecated, the use of `--prefix` is preferred.'		)
 parser.add_argument('--xlm_language'   , type=SCREAMING_SNAKE_CASE   , default=''   , help='Optional language when used with the XLM model.'		)

 parser.add_argument('--seed'   , type=SCREAMING_SNAKE_CASE   , default=42   , help='random seed for initialization'		)
 parser.add_argument('--no_cuda'   , action='store_true'   , help='Avoid using CUDA when available'		)
 parser.add_argument('--num_return_sequences'   , type=SCREAMING_SNAKE_CASE   , default=1   , help='The number of samples to generate.'		)
 parser.add_argument(
     '--fp16'   , action='store_true'   , help='Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit'   , )
 parser.add_argument('--jit'   , action='store_true'   , help='Whether or not to use jit trace to accelerate inference'		)
 __lowerCAmelCase:       Optional[Any]            =				parser.parse_args()

 __lowerCAmelCase:       Dict            =				torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu'		)
 __lowerCAmelCase:       Any            =				0 if args.no_cuda else torch.cuda.device_count()

 logger.warning(f'''device: {args.device}, n_gpu: {args.n_gpu}, 16-bits training: {args.fpaa}'''		)

 set_seed(SCREAMING_SNAKE_CASE		)

 # Initialize the model and tokenizer
 try:
  __lowerCAmelCase:       Any            =				args.model_type.lower()
  __lowerCAmelCase:       List[Any]            =				MODEL_CLASSES[args.model_type]
 except KeyError:
  raise KeyError('the model {} you specified is not supported. You are welcome to add it and open a PR :)'		)

 __lowerCAmelCase:       List[str]            =				tokenizer_class.from_pretrained(args.model_name_or_path		)
 if tokenizer.pad_token is None:
  __lowerCAmelCase:       Any            =				tokenizer.eos_token
 __lowerCAmelCase:       Any            =				model_class.from_pretrained(args.model_name_or_path		)
 model.to(args.device		)

 if args.fpaa:
  model.half()
 __lowerCAmelCase:       Optional[Any]            =				getattr(model.config   , 'max_position_embeddings'   , 0		)
 __lowerCAmelCase:       Union[str, Any]            =				adjust_length_to_model(args.length   , max_sequence_length=SCREAMING_SNAKE_CASE		)
 logger.info(SCREAMING_SNAKE_CASE		)

 __lowerCAmelCase:       Optional[Any]            =				args.prompt if args.prompt else input('Model prompt >>> '		)

 # Different models need different input formatting and/or extra arguments
 __lowerCAmelCase:       Any            =				args.model_type in PREPROCESSING_FUNCTIONS.keys()
 if requires_preprocessing:
  __lowerCAmelCase:       Union[str, Any]            =				PREPROCESSING_FUNCTIONS.get(args.model_type		)
  __lowerCAmelCase:       Tuple            =				prepare_input(SCREAMING_SNAKE_CASE   , SCREAMING_SNAKE_CASE   , SCREAMING_SNAKE_CASE   , SCREAMING_SNAKE_CASE		)

  if model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
   __lowerCAmelCase:       List[Any]            =				{'add_space_before_punct_symbol': True}
  else:
   __lowerCAmelCase:       Dict            =				{}

  __lowerCAmelCase:       str            =				tokenizer.encode(
      SCREAMING_SNAKE_CASE   , add_special_tokens=SCREAMING_SNAKE_CASE   , return_tensors='pt'   , **SCREAMING_SNAKE_CASE		)
 else:
  __lowerCAmelCase:       Optional[int]            =				args.prefix if args.prefix else args.padding_text
  __lowerCAmelCase:       Any            =				tokenizer.encode(prefix + prompt_text   , add_special_tokens=SCREAMING_SNAKE_CASE   , return_tensors='pt'		)
 __lowerCAmelCase:       Any            =				encoded_prompt.to(args.device		)

 if encoded_prompt.size()[-1] == 0:
  __lowerCAmelCase:       Union[str, Any]            =				None
 else:
  __lowerCAmelCase:       Dict            =				encoded_prompt

 if args.jit:
  __lowerCAmelCase:       str            =				['enable jit']
  __lowerCAmelCase:       Dict            =				prepare_jit_inputs(SCREAMING_SNAKE_CASE   , SCREAMING_SNAKE_CASE   , SCREAMING_SNAKE_CASE		)
  torch._C._jit_set_texpr_fuser_enabled(SCREAMING_SNAKE_CASE		)
  __lowerCAmelCase:       Dict            =				False
  if hasattr(SCREAMING_SNAKE_CASE   , 'forward'		):
   __lowerCAmelCase:       Union[str, Any]            =				inspect.signature(model.forward		)
  else:
   __lowerCAmelCase:       str            =				inspect.signature(model.__call__		)
  __lowerCAmelCase:       List[Any]            =				tuple(jit_inputs[key] for key in sig.parameters if jit_inputs.get(SCREAMING_SNAKE_CASE   , SCREAMING_SNAKE_CASE		) is not None		)
  __lowerCAmelCase:       Dict            =				torch.jit.trace(SCREAMING_SNAKE_CASE   , SCREAMING_SNAKE_CASE   , strict=SCREAMING_SNAKE_CASE		)
  __lowerCAmelCase:       int            =				torch.jit.freeze(traced_model.eval()		)
  traced_model(*SCREAMING_SNAKE_CASE		)
  traced_model(*SCREAMING_SNAKE_CASE		)

  __lowerCAmelCase:       int            =				_ModelFallbackWrapper(SCREAMING_SNAKE_CASE   , SCREAMING_SNAKE_CASE		)

 __lowerCAmelCase:       Tuple            =				model.generate(
     input_ids=SCREAMING_SNAKE_CASE   , max_length=args.length + len(encoded_prompt[0]		)   , temperature=args.temperature   , top_k=args.k   , top_p=args.p   , repetition_penalty=args.repetition_penalty   , do_sample=SCREAMING_SNAKE_CASE   , num_return_sequences=args.num_return_sequences   , )

 # Remove the batch dimension when returning multiple sequences
 if len(output_sequences.shape		) > 2:
  output_sequences.squeeze_()

 __lowerCAmelCase:       Optional[int]            =				[]

 for generated_sequence_idx, generated_sequence in enumerate(SCREAMING_SNAKE_CASE		):
  print(f'''=== GENERATED SEQUENCE {generated_sequence_idx + 1} ==='''		)
  __lowerCAmelCase:       Optional[Any]            =				generated_sequence.tolist()

  # Decode text
  __lowerCAmelCase:       Optional[int]            =				tokenizer.decode(SCREAMING_SNAKE_CASE   , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE		)

  # Remove all text after the stop token
  __lowerCAmelCase:       Optional[Any]            =				text[: text.find(args.stop_token		) if args.stop_token else None]

  # Add the prompt at the beginning of the sequence. Remove the excess text that was used for pre-processing
  __lowerCAmelCase:       List[str]            =				(
      prompt_text + text[len(tokenizer.decode(encoded_prompt[0]   , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE		)		) :]
  )

  generated_sequences.append(SCREAMING_SNAKE_CASE		)
  print(SCREAMING_SNAKE_CASE		)

 return generated_sequences


if __name__ == "__main__":
  main()








def _a			(	SCREAMING_SNAKE_CASE		:      int = 10_00		)   ->   int:

 """simple docstring"""






 __lowerCAmelCase:       Union[str, Any]            =				[0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7, 9, 8, 8]
 # number of letters in twenty, thirty, ..., ninety (0 for numbers less than
 # 20 due to inconsistency in teens)
 __lowerCAmelCase:       Union[str, Any]            =				[0, 0, 6, 6, 5, 5, 5, 7, 6, 6]

 __lowerCAmelCase:       Optional[int]            =				0

 for i in range(1   , n + 1		):
  if i < 10_00:
   if i >= 1_00:
    # add number of letters for "n hundred"
    count += ones_counts[i // 1_00] + 7

    if i % 1_00 != 0:
     # add number of letters for "and" if number is not multiple
     # of 100
     count += 3

   if 0 < i % 1_00 < 20:
    # add number of letters for one, two, three, ..., nineteen
    # (could be combined with below if not for inconsistency in
    # teens)
    count += ones_counts[i % 1_00]
   else:
    # add number of letters for twenty, twenty one, ..., ninety
    # nine
    count += ones_counts[i % 10]
    count += tens_counts[(i % 1_00 - i % 10) // 10]
  else:
   count += ones_counts[i // 10_00] + 8
 return count


if __name__ == "__main__":
  print(solution(int(input().strip())))





