

'''simple docstring'''







import json
import os
from pathlib import Path
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple, Union

import sentencepiece

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


__lowerCamelCase									=     logging.get_logger(__name__)

__lowerCamelCase									=     '''▁'''

__lowerCamelCase									=     {
    '''vocab_file''': '''vocab.json''',
    '''spm_file''': '''sentencepiece.bpe.model''',
}

__lowerCamelCase									=     {
    '''vocab_file''': {
        '''facebook/s2t-small-librispeech-asr''': (
            '''https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/vocab.json'''
        ),
    },
    '''spm_file''': {
        '''facebook/s2t-small-librispeech-asr''': (
            '''https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/sentencepiece.bpe.model'''
        )
    },
}

__lowerCamelCase									=     {
    '''facebook/s2t-small-librispeech-asr''': 1024,
}

__lowerCamelCase									=     ['''pt''', '''fr''', '''ru''', '''nl''', '''ro''', '''it''', '''es''', '''de''']

__lowerCamelCase									=     {'''mustc''': MUSTC_LANGS}


class        A__   (   _snake_case      ):
    lowercase						       =		VOCAB_FILES_NAMES
    lowercase						       =		PRETRAINED_VOCAB_FILES_MAP
    lowercase						       =		MAX_MODEL_INPUT_SIZES
    lowercase						       =		["input_ids", "attention_mask"]

    lowercase						       =		[]



    def __init__(       self		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__="<s>"		,					UpperCamelCase__="</s>"		,					UpperCamelCase__="<pad>"		,					UpperCamelCase__="<unk>"		,					UpperCamelCase__=False		,					UpperCamelCase__=False		,					UpperCamelCase__=None		,					UpperCamelCase__=None		,					UpperCamelCase__ = None		,					**UpperCamelCase__		,					)    ->   None:





           '''simple docstring'''
           A_						       =   {} if sp_model_kwargs is None else sp_model_kwargs

           super().__init__(
               bos_token=UpperCamelCase__		,					eos_token=UpperCamelCase__		,					unk_token=UpperCamelCase__		,					pad_token=UpperCamelCase__		,					do_upper_case=UpperCamelCase__		,					do_lower_case=UpperCamelCase__		,					tgt_lang=UpperCamelCase__		,					lang_codes=UpperCamelCase__		,					sp_model_kwargs=self.sp_model_kwargs		,					**UpperCamelCase__		,					)
           A_						       =   do_upper_case
           A_						       =   do_lower_case

           A_						       =   load_json(UpperCamelCase__							)
           A_						       =   {v: k for k, v in self.encoder.items()}
           A_						       =   spm_file
           A_						       =   load_spm(UpperCamelCase__		,					self.sp_model_kwargs							)

           if lang_codes is not None:
                  A_						       =   lang_codes
                  A_						       =   LANGUAGES[lang_codes]
                  A_						       =   [f'''<lang:{lang}>''' for lang in self.langs]
                  A_						       =   {lang: self.sp_model.PieceToId(f'''<lang:{lang}>'''							) for lang in self.langs}

                  A_						       =   self.lang_tokens
                  A_						       =   tgt_lang if tgt_lang is not None else self.langs[0]

                  self.set_tgt_lang_special_tokens(self._tgt_lang							)
           else:
                  A_						       =   {}



    @property
    def        snake_case_      (       self							)    ->   int:





           '''simple docstring'''
           return len(self.encoder							)



    @property
    def        snake_case_      (       self							)    ->   str:





           '''simple docstring'''
           return self._tgt_lang



    @tgt_lang.setter
    def        snake_case_      (       self		,					UpperCamelCase__							)    ->   None:





           '''simple docstring'''
           A_						       =   new_tgt_lang
           self.set_tgt_lang_special_tokens(UpperCamelCase__							)



    def        snake_case_      (       self		,					UpperCamelCase__							)    ->   None:





           '''simple docstring'''
           A_						       =   self.lang_code_to_id[tgt_lang]
           A_						       =   [lang_code_id]



    def        snake_case_      (       self		,					UpperCamelCase__							)    ->   List[str]:





           '''simple docstring'''
           return self.sp_model.encode(UpperCamelCase__		,					out_type=UpperCamelCase__							)



    def        snake_case_      (       self		,					UpperCamelCase__							)    ->   Any:





           '''simple docstring'''
           return self.encoder.get(UpperCamelCase__		,					self.encoder[self.unk_token]							)



    def        snake_case_      (       self		,					UpperCamelCase__							)    ->   str:





           '''simple docstring'''
           return self.decoder.get(UpperCamelCase__		,					self.unk_token							)



    def        snake_case_      (       self		,					UpperCamelCase__							)    ->   str:





           '''simple docstring'''
           A_						       =   []
           A_						       =   """"""
           for token in tokens:
                  # make sure that special tokens are not decoded using sentencepiece model
                  if token in self.all_special_tokens:
                         A_						       =   self.sp_model.decode(UpperCamelCase__							)
                         out_string += (decoded.upper() if self.do_upper_case else decoded) + token + " "
                         A_						       =   []
                  else:
                         current_sub_tokens.append(UpperCamelCase__							)
           A_						       =   self.sp_model.decode(UpperCamelCase__							)
           out_string += decoded.upper() if self.do_upper_case else decoded
           return out_string.strip()



    def        snake_case_      (       self		,					UpperCamelCase__		,					UpperCamelCase__=None							)    ->   List[int]:





           '''simple docstring'''
           if token_ids_a is None:
                  return self.prefix_tokens + token_ids_a + [self.eos_token_id]
           # We don't expect to process pairs, but leave the pair logic for API consistency
           return self.prefix_tokens + token_ids_a + token_ids_a + [self.eos_token_id]



    def        snake_case_      (       self		,					UpperCamelCase__		,					UpperCamelCase__ = None		,					UpperCamelCase__ = False							)    ->   List[int]:





           '''simple docstring'''

           if already_has_special_tokens:
                  return super().get_special_tokens_mask(
                      token_ids_a=UpperCamelCase__		,					token_ids_a=UpperCamelCase__		,					already_has_special_tokens=UpperCamelCase__							)

           A_						       =   [1] * len(self.prefix_tokens							)
           A_						       =   [1]
           if token_ids_a is None:
                  return prefix_ones + ([0] * len(UpperCamelCase__							)) + suffix_ones
           return prefix_ones + ([0] * len(UpperCamelCase__							)) + ([0] * len(UpperCamelCase__							)) + suffix_ones



    def        snake_case_      (       self							)    ->   Dict:





           '''simple docstring'''
           A_						       =   self.encoder.copy()
           vocab.update(self.added_tokens_encoder							)
           return vocab



    def __getstate__(       self							)    ->   Dict:





           '''simple docstring'''
           A_						       =   self.__dict__.copy()
           A_						       =   None
           return state



    def __setstate__(       self		,					UpperCamelCase__							)    ->   None:





           '''simple docstring'''
           A_						       =   d

           # for backward compatibility
           if not hasattr(self		,					"""sp_model_kwargs"""							):
                  A_						       =   {}

           A_						       =   load_spm(self.spm_file		,					self.sp_model_kwargs							)







    def        snake_case_      (       self		,					UpperCamelCase__		,					UpperCamelCase__ = None							)    ->   Tuple[str]:





           '''simple docstring'''
           A_						       =   Path(UpperCamelCase__							)
           assert save_dir.is_dir(), f'''{save_directory} should be a directory'''
           A_						       =   save_dir / (
               (filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""vocab_file"""]
           )
           A_						       =   save_dir / (
               (filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""spm_file"""]
           )

           save_json(self.encoder		,					UpperCamelCase__							)

           if os.path.abspath(self.spm_file							) != os.path.abspath(UpperCamelCase__							) and os.path.isfile(self.spm_file							):
                  copyfile(self.spm_file		,					UpperCamelCase__							)
           elif not os.path.isfile(self.spm_file							):
                  with open(UpperCamelCase__		,					"""wb"""							) as fi:
                         A_						       =   self.sp_model.serialized_model_proto()
                         fi.write(UpperCamelCase__							)

           return (str(UpperCamelCase__							), str(UpperCamelCase__							))

def    UpperCAmelCase__     (   UpperCAmelCase__,							UpperCAmelCase__					)      ->      sentencepiece.SentencePieceProcessor:
       A_						       =   sentencepiece.SentencePieceProcessor(**UpperCAmelCase__					)
       spm.Load(str(UpperCAmelCase__					)					)
       return spm
def    UpperCAmelCase__     (   UpperCAmelCase__					)      ->      Union[Dict, List]:
       with open(UpperCAmelCase__,							"""r"""					) as f:
              return json.load(UpperCAmelCase__					)







def    UpperCAmelCase__     (   UpperCAmelCase__,							UpperCAmelCase__					)      ->      None:
       with open(UpperCAmelCase__,							"""w"""					) as f:
              json.dump(UpperCAmelCase__,							UpperCAmelCase__,							indent=2					)



'''simple docstring'''







# Copyright 2022 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.

import argparse
import os
import subprocess

from packaging.version import Version, parse

from accelerate.commands.config.config_args import default_config_file, load_config_from_file


__lowerCamelCase									=     '''Run commands across TPU VMs for initial setup before running `accelerate launch`.'''
def    UpperCAmelCase__     (   UpperCAmelCase__=None					)      ->      List[str]:
       if subparsers is not None:
              A_						       =   subparsers.add_parser("""tpu-config""",							description=_description					)
       else:
              A_						       =   argparse.ArgumentParser("""Accelerate tpu-config command""",							description=_description					)
       # Core arguments
       A_						       =   parser.add_argument_group(
           """Config Arguments""",							"""Arguments that can be configured through `accelerate config`."""					)
       config_args.add_argument(
           """--config_file""",							type=UpperCAmelCase__,							default=UpperCAmelCase__,							help="""Path to the config file to use for accelerate.""",							)
       config_args.add_argument(
           """--tpu_name""",							default=UpperCAmelCase__,							help="""The name of the TPU to use. If not specified, will use the TPU specified in the config file.""",							)
       config_args.add_argument(
           """--tpu_zone""",							default=UpperCAmelCase__,							help="""The zone of the TPU to use. If not specified, will use the zone specified in the config file.""",							)
       A_						       =   parser.add_argument_group("""TPU Arguments""",							"""Arguments for options ran inside the TPU."""					)
       pod_args.add_argument(
           """--use_alpha""",							action="""store_true""",							help="""Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.""",							)
       pod_args.add_argument(
           """--command_file""",							default=UpperCAmelCase__,							help="""The path to the file containing the commands to run on the pod on startup.""",							)
       pod_args.add_argument(
           """--command""",							action="""append""",							nargs="""+""",							help="""A command to run on the pod. Can be passed multiple times.""",							)
       pod_args.add_argument(
           """--install_accelerate""",							action="""store_true""",							help="""Whether to install accelerate on the pod. Defaults to False.""",							)
       pod_args.add_argument(
           """--accelerate_version""",							default="""latest""",							help="""The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify 'dev' to install from GitHub.""",							)
       pod_args.add_argument(
           """--debug""",							action="""store_true""",							help="""If set, will print the command that would be run instead of running it."""					)

       if subparsers is not None:
              parser.set_defaults(func=UpperCAmelCase__					)
       return parser
def    UpperCAmelCase__     (   UpperCAmelCase__					)      ->      List[Any]:
       A_						       =   None

       # Get the default from the config file if it exists.
       if args.config_file is not None or os.path.isfile(UpperCAmelCase__					):
              A_						       =   load_config_from_file(args.config_file					)
              if not args.command_file and defaults.command_file is not None and not args.command:
                     A_						       =   defaults.command_file
              if not args.command and defaults.commands is not None:
                     A_						       =   defaults.commands
              if not args.tpu_name:
                     A_						       =   defaults.tpu_name
              if not args.tpu_zone:
                     A_						       =   defaults.tpu_zone
       if args.accelerate_version == "dev":
              A_						       =   """git+https://github.com/huggingface/accelerate.git"""
       elif args.accelerate_version == "latest":
              A_						       =   """accelerate -U"""
       elif isinstance(parse(args.accelerate_version					),							UpperCAmelCase__					):
              A_						       =   F'''accelerate=={args.accelerate_version}'''

       if not args.command_file and not args.command:
              raise ValueError("""You must specify either a command file or a command to run on the pod."""					)

       if args.command_file:
              with open(args.command_file,							"""r"""					) as f:
                     A_						       =   [f.read().splitlines()]

    # To turn list of lists into list of strings
       if isinstance(args.command[0],							UpperCAmelCase__					):
              A_						       =   [line for cmd in args.command for line in cmd]
       # Default to the shared folder and install accelerate
       A_						       =   ["""cd /usr/share"""]
       if args.install_accelerate:
              new_cmd += [F'''pip install {args.accelerate_version}''']
       new_cmd += args.command
       A_						       =   """; """.join(UpperCAmelCase__					)

       # Then send it to gcloud
       # Eventually try to use google-api-core to do this instead of subprocess
       A_						       =   ["""gcloud"""]
       if args.use_alpha:
              cmd += ["alpha"]
       cmd += [
           "compute",
           "tpus",
           "tpu-vm",
           "ssh",
           args.tpu_name,
           "--zone",
           args.tpu_zone,
           "--command",
           args.command,
           "--worker",
           "all",
       ]
       if args.debug:
              print(F'''Running {" ".join(UpperCAmelCase__					)}'''					)
              return
       subprocess.run(UpperCAmelCase__					)
       print("""Successfully setup pod."""					)







def    UpperCAmelCase__     (   )      ->      int:
       A_						       =   tpu_command_parser()
       A_						       =   parser.parse_args()

       tpu_command_launcher(UpperCAmelCase__					)
