
import json
import logging
import os
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Union

import datasets
import numpy as np
import torch
import torchaudio
from packaging import version
from torch import nn

import transformers
from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process


if is_apex_available():
      from apex import amp


if version.parse(version.parse(torch.__version__).base_version) >= version.parse("""1.6"""):
      _lowerCamelCase					   =True
      from torch.cuda.amp import autocast

_lowerCamelCase					   =logging.getLogger(__name__)





def     _a					(						lowerCamelCase=None,	lowerCamelCase=None							):
 return field(default_factory=lambda: default,	metadata=lowerCamelCase							)





@dataclass
class 							A__		:
      _UpperCAmelCase				:    str           =			field(
          metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""})
      _UpperCAmelCase				:    Optional[str]           =			field(
          default=__SCREAMING_SNAKE_CASE  ,   metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}  ,   )
      _UpperCAmelCase				:    Optional[bool]           =			field(
          default=__SCREAMING_SNAKE_CASE  ,   metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""})
      _UpperCAmelCase				:    Optional[float]           =			field(
          default=0.1  ,   metadata={"""help""": """The dropout ratio for the attention probabilities."""})
      _UpperCAmelCase				:    Optional[float]           =			field(
          default=0.1  ,   metadata={"""help""": """The dropout ratio for activations inside the fully connected layer."""})
      _UpperCAmelCase				:    Optional[float]           =			field(
          default=0.1  ,   metadata={
              """help""": """The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler."""
          }  ,   )
      _UpperCAmelCase				:    Optional[float]           =			field(
          default=0.1  ,   metadata={"""help""": """The dropout probabilitiy for all 1D convolutional layers in feature extractor."""}  ,   )
      _UpperCAmelCase				:    Optional[float]           =			field(
          default=0.05  ,   metadata={
              """help""": (
                  """Propability of each feature vector along the time axis to be chosen as the start of the vector"""
                  """span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature"""
                  """vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``."""
              )
          }  ,   )
      _UpperCAmelCase				:    Optional[float]           =			field(default=0.0  ,   metadata={"""help""": """The LayerDrop probability."""})





@dataclass
class 							A__		:
      _UpperCAmelCase				:    Optional[str]           =			field(
          default=__SCREAMING_SNAKE_CASE  ,   metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""})
      _UpperCAmelCase				:    Optional[str]           =			field(
          default="""train+validation"""  ,   metadata={
              """help""": """The name of the training data set split to use (via the datasets library). Defaults to 'train'"""
          }  ,   )
      _UpperCAmelCase				:    bool           =			field(
          default=__SCREAMING_SNAKE_CASE  ,   metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""})
      _UpperCAmelCase				:    Optional[int]           =			field(
          default=__SCREAMING_SNAKE_CASE  ,   metadata={"""help""": """The number of processes to use for the preprocessing."""}  ,   )
      _UpperCAmelCase				:    Optional[int]           =			field(
          default=__SCREAMING_SNAKE_CASE  ,   metadata={
              """help""": (
                  """For debugging purposes or quicker training, truncate the number of training examples to this """
                  """value if set."""
              )
          }  ,   )
      _UpperCAmelCase				:    Optional[int]           =			field(
          default=__SCREAMING_SNAKE_CASE  ,   metadata={
              """help""": (
                  """For debugging purposes or quicker training, truncate the number of validation examples to this """
                  """value if set."""
              )
          }  ,   )
      _UpperCAmelCase				:    List[str]           =			list_field(
          default=[""",""", """?""", """.""", """!""", """-""", """;""", """:""", """\"\"""", """%""", """'""", """\"""", """�"""]  ,   metadata={"""help""": """A list of characters to remove from the transcripts."""}  ,   )





@dataclass
class 							A__		:
      _UpperCAmelCase				:    WavaVecaProcessor
      _UpperCAmelCase				:    Union[bool, str]           =			True
      _UpperCAmelCase				:    Optional[int]           =			None
      _UpperCAmelCase				:    Optional[int]           =			None
      _UpperCAmelCase				:    Optional[int]           =			None
      _UpperCAmelCase				:    Optional[int]           =			None
      def __call__(      self    ,  __magic_name__      ):
       # split inputs and labels since they have to be of different lenghts and need
       # different padding methods
       lowerCamelCase		:	str							=      [{"""input_values""": feature["""input_values"""]} for feature in features]
       lowerCamelCase		:	Any							=      [{"""input_ids""": feature["""labels"""]} for feature in features]

       lowerCamelCase		:	List[str]							=      self.processor.pad(
           __magic_name__    ,  padding=self.padding    ,  max_length=self.max_length    ,  pad_to_multiple_of=self.pad_to_multiple_of    ,  return_tensors="""pt"""    ,  )
       lowerCamelCase		:	Optional[Any]							=      self.processor.pad(
           labels=__magic_name__    ,  padding=self.padding    ,  max_length=self.max_length_labels    ,  pad_to_multiple_of=self.pad_to_multiple_of_labels    ,  return_tensors="""pt"""    ,  )

       # replace padding with -100 to ignore loss correctly
       lowerCamelCase		:	int							=      labels_batch["""input_ids"""].masked_fill(labels_batch.attention_mask.ne(1      )    ,  -1_0_0      )

       lowerCamelCase		:	Dict							=      labels

       return batch





class 							A__		(	__SCREAMING_SNAKE_CASE):
      def 						UpperCamelCase__							(      self    ,  __magic_name__    ,  __magic_name__      ):
       model.train()
       lowerCamelCase		:	int							=      self._prepare_inputs(__magic_name__      )

       if self.use_amp:
        with autocast():
         lowerCamelCase		:	str							=      self.compute_loss(__magic_name__    ,  __magic_name__      )
       else:
        lowerCamelCase		:	Any							=      self.compute_loss(__magic_name__    ,  __magic_name__      )

       if self.args.n_gpu > 1:
        if model.module.config.ctc_loss_reduction == "mean":
         lowerCamelCase		:	int							=      loss.mean()
        elif model.module.config.ctc_loss_reduction == "sum":
         lowerCamelCase		:	List[str]							=      loss.sum() / (inputs["""labels"""] >= 0).sum()
        else:
         raise ValueError(F'''{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']'''      )

       if self.args.gradient_accumulation_steps > 1:
        lowerCamelCase		:	Any							=      loss / self.args.gradient_accumulation_steps

       if self.use_amp:
        self.scaler.scale(__magic_name__      ).backward()
       elif self.use_apex:
        with amp.scale_loss(__magic_name__    ,  self.optimizer      ) as scaled_loss:
         scaled_loss.backward()
       elif self.deepspeed:
        self.deepspeed.backward(__magic_name__      )
       else:
        loss.backward()

       return loss.detach()





def     _a					(						):
 # See all possible arguments in src/transformers/training_args.py
 # or by passing the --help flag to this script.
 # We now keep distinct sets of args, for a cleaner separation of concerns.

 lowerCamelCase		:	str							=      HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)							)
 if len(sys.argv							) == 2 and sys.argv[1].endswith(""".json"""							):
  # If we pass only one argument to the script and it's the path to a json file,
  # let's parse it to get our arguments.
  lowerCamelCase			,    lowerCamelCase			,    lowerCamelCase		:	Optional[int]							=      parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]							)							)
 else:
  lowerCamelCase			,    lowerCamelCase			,    lowerCamelCase		:	Optional[Any]							=      parser.parse_args_into_dataclasses()

 # Detecting last checkpoint.
 lowerCamelCase		:	Any							=      None
 if os.path.isdir(training_args.output_dir							) and training_args.do_train and not training_args.overwrite_output_dir:
  lowerCamelCase		:	Optional[int]							=      get_last_checkpoint(training_args.output_dir							)
  if last_checkpoint is None and len(os.listdir(training_args.output_dir							)							) > 0:
   raise ValueError(
       F'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
       """Use --overwrite_output_dir to overcome."""							)
  elif last_checkpoint is not None:
   logger.info(
       F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
       """the `--output_dir` or add `--overwrite_output_dir` to train from scratch."""							)

    # Setup logging
 logging.basicConfig(
     format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""",	datefmt="""%m/%d/%Y %H:%M:%S""",	handlers=[logging.StreamHandler(sys.stdout							)],	)
 logger.setLevel(logging.INFO if is_main_process(training_args.local_rank							) else logging.WARN							)

 # Log on each process the small summary:
 logger.warning(
     F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'''
     + F'''distributed training: {bool(training_args.local_rank != -1							)}, 16-bits training: {training_args.fpaa}'''							)
 # Set the verbosity to info of the Transformers logger (on main process only):
 if is_main_process(training_args.local_rank							):
  transformers.utils.logging.set_verbosity_info()
 logger.info("""Training/evaluation parameters %s""",	lowerCamelCase							)

 # Set seed before initializing model.
 set_seed(training_args.seed							)

 # Get the datasets:
 lowerCamelCase		:	Dict							=      datasets.load_dataset(
     """common_voice""",	data_args.dataset_config_name,	split=data_args.train_split_name							)
 lowerCamelCase		:	Optional[Any]							=      datasets.load_dataset("""common_voice""",	data_args.dataset_config_name,	split="""test"""							)

 # Create and save tokenizer
 lowerCamelCase		:	Optional[Any]							=      F'''[{"".join(data_args.chars_to_ignore							)}]'''

 def remove_special_characters(lowerCamelCase							):
  lowerCamelCase		:	Union[str, Any]							=      re.sub(lowerCamelCase,	"""""",	batch["""sentence"""]							).lower() + """ """
  return batch

 lowerCamelCase		:	int							=      train_dataset.map(lowerCamelCase,	remove_columns=["""sentence"""]							)
 lowerCamelCase		:	Any							=      eval_dataset.map(lowerCamelCase,	remove_columns=["""sentence"""]							)

 def extract_all_chars(lowerCamelCase							):
  lowerCamelCase		:	int							=      """ """.join(batch["""text"""]							)
  lowerCamelCase		:	int							=      list(set(lowerCamelCase							)							)
  return {"vocab": [vocab], "all_text": [all_text]}

 lowerCamelCase		:	Optional[int]							=      train_dataset.map(
     lowerCamelCase,	batched=lowerCamelCase,	batch_size=-1,	keep_in_memory=lowerCamelCase,	remove_columns=train_dataset.column_names,	)
 lowerCamelCase		:	Tuple							=      train_dataset.map(
     lowerCamelCase,	batched=lowerCamelCase,	batch_size=-1,	keep_in_memory=lowerCamelCase,	remove_columns=eval_dataset.column_names,	)

 lowerCamelCase		:	Union[str, Any]							=      list(set(vocab_train["""vocab"""][0]							) | set(vocab_test["""vocab"""][0]							)							)
 lowerCamelCase		:	Tuple							=      {v: k for k, v in enumerate(lowerCamelCase							)}
 lowerCamelCase		:	Optional[Any]							=      vocab_dict[""" """]
 del vocab_dict[" "]
 lowerCamelCase		:	str							=      len(lowerCamelCase							)
 lowerCamelCase		:	str							=      len(lowerCamelCase							)

 with open("""vocab.json""",	"""w"""							) as vocab_file:
  json.dump(lowerCamelCase,	lowerCamelCase							)

 # Load pretrained model and tokenizer
 #
 # Distributed training:
 # The .from_pretrained methods guarantee that only one local process can concurrently
 # download model & vocab.
 lowerCamelCase		:	Dict							=      WavaVecaCTCTokenizer(
     """vocab.json""",	unk_token="""[UNK]""",	pad_token="""[PAD]""",	word_delimiter_token="""|""",	)
 lowerCamelCase		:	int							=      WavaVecaFeatureExtractor(
     feature_size=1,	sampling_rate=1_6000,	padding_value=0.0,	do_normalize=lowerCamelCase,	return_attention_mask=lowerCamelCase							)
 lowerCamelCase		:	Optional[int]							=      WavaVecaProcessor(feature_extractor=lowerCamelCase,	tokenizer=lowerCamelCase							)
 lowerCamelCase		:	Dict							=      WavaVecaForCTC.from_pretrained(
     model_args.model_name_or_path,	cache_dir=model_args.cache_dir,	activation_dropout=model_args.activation_dropout,	attention_dropout=model_args.attention_dropout,	hidden_dropout=model_args.hidden_dropout,	feat_proj_dropout=model_args.feat_proj_dropout,	mask_time_prob=model_args.mask_time_prob,	gradient_checkpointing=training_args.gradient_checkpointing,	layerdrop=model_args.layerdrop,	ctc_loss_reduction="""mean""",	pad_token_id=processor.tokenizer.pad_token_id,	vocab_size=len(processor.tokenizer							),	)

 if data_args.max_train_samples is not None:
  lowerCamelCase		:	Optional[int]							=      min(len(lowerCamelCase							),	data_args.max_train_samples							)
  lowerCamelCase		:	List[str]							=      train_dataset.select(range(lowerCamelCase							)							)

 if data_args.max_val_samples is not None:
  lowerCamelCase		:	str							=      eval_dataset.select(range(data_args.max_val_samples							)							)

 lowerCamelCase		:	Dict							=      torchaudio.transforms.Resample(4_8000,	1_6000							)

 # Preprocessing the datasets.
 # We need to read the aduio files as arrays and tokenize the targets.
 def speech_file_to_array_fn(lowerCamelCase							):
  lowerCamelCase			,    lowerCamelCase		:	Optional[Any]							=      torchaudio.load(batch["""path"""]							)
  lowerCamelCase		:	Optional[Any]							=      resampler(lowerCamelCase							).squeeze().numpy()
  lowerCamelCase		:	List[str]							=      1_6000
  lowerCamelCase		:	Any							=      batch["""text"""]
  return batch

 lowerCamelCase		:	int							=      train_dataset.map(
     lowerCamelCase,	remove_columns=train_dataset.column_names,	num_proc=data_args.preprocessing_num_workers,	)
 lowerCamelCase		:	Optional[Any]							=      eval_dataset.map(
     lowerCamelCase,	remove_columns=eval_dataset.column_names,	num_proc=data_args.preprocessing_num_workers,	)

 def prepare_dataset(lowerCamelCase							):
  # check that all files have the correct sampling rate
  assert (
      len(set(batch["""sampling_rate"""]							)							) == 1
  ), F'''Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}.'''

  lowerCamelCase		:	Any							=      processor(
      audio=batch["""speech"""],	text=batch["""target_text"""],	sampling_rate=batch["""sampling_rate"""][0]							)
  batch.update(lowerCamelCase							)
  return batch

 lowerCamelCase		:	Any							=      train_dataset.map(
     lowerCamelCase,	remove_columns=train_dataset.column_names,	batch_size=training_args.per_device_train_batch_size,	batched=lowerCamelCase,	num_proc=data_args.preprocessing_num_workers,	)
 lowerCamelCase		:	Union[str, Any]							=      eval_dataset.map(
     lowerCamelCase,	remove_columns=eval_dataset.column_names,	batch_size=training_args.per_device_train_batch_size,	batched=lowerCamelCase,	num_proc=data_args.preprocessing_num_workers,	)

 # Metric
 lowerCamelCase		:	List[str]							=      datasets.load_metric("""wer"""							)

 def compute_metrics(lowerCamelCase							):
  lowerCamelCase		:	str							=      pred.predictions
  lowerCamelCase		:	Optional[Any]							=      np.argmax(lowerCamelCase,	axis=-1							)

  lowerCamelCase		:	Union[str, Any]							=      processor.tokenizer.pad_token_id

  lowerCamelCase		:	Optional[int]							=      processor.batch_decode(lowerCamelCase							)
  # we do not want to group tokens when computing the metrics
  lowerCamelCase		:	Any							=      processor.batch_decode(pred.label_ids,	group_tokens=lowerCamelCase							)

  lowerCamelCase		:	Union[str, Any]							=      wer_metric.compute(predictions=lowerCamelCase,	references=lowerCamelCase							)

  return {"wer": wer}

 if model_args.freeze_feature_extractor:
  model.freeze_feature_extractor()

 # Data collator
 lowerCamelCase		:	Dict							=      DataCollatorCTCWithPadding(processor=lowerCamelCase,	padding=lowerCamelCase							)

 # Initialize our Trainer
 lowerCamelCase		:	Tuple							=      CTCTrainer(
     model=lowerCamelCase,	data_collator=lowerCamelCase,	args=lowerCamelCase,	compute_metrics=lowerCamelCase,	train_dataset=train_dataset if training_args.do_train else None,	eval_dataset=eval_dataset if training_args.do_eval else None,	tokenizer=processor.feature_extractor,	)

 # Training
 if training_args.do_train:
  if last_checkpoint is not None:
   lowerCamelCase		:	Optional[Any]							=      last_checkpoint
  elif os.path.isdir(model_args.model_name_or_path							):
   lowerCamelCase		:	str							=      model_args.model_name_or_path
  else:
   lowerCamelCase		:	int							=      None

  # Save the feature_extractor and the tokenizer
  if is_main_process(training_args.local_rank							):
   processor.save_pretrained(training_args.output_dir							)

  lowerCamelCase		:	Tuple							=      trainer.train(resume_from_checkpoint=lowerCamelCase							)
  trainer.save_model()

  lowerCamelCase		:	Tuple							=      train_result.metrics
  lowerCamelCase		:	Optional[Any]							=      (
      data_args.max_train_samples if data_args.max_train_samples is not None else len(lowerCamelCase							)
  )
  lowerCamelCase		:	Tuple							=      min(lowerCamelCase,	len(lowerCamelCase							)							)

  trainer.log_metrics("""train""",	lowerCamelCase							)
  trainer.save_metrics("""train""",	lowerCamelCase							)
  trainer.save_state()

 # Evaluation
 lowerCamelCase		:	Tuple							=      {}
 if training_args.do_eval:
  logger.info("""*** Evaluate ***"""							)
  lowerCamelCase		:	List[Any]							=      trainer.evaluate()
  lowerCamelCase		:	Dict							=      data_args.max_val_samples if data_args.max_val_samples is not None else len(lowerCamelCase							)
  lowerCamelCase		:	List[str]							=      min(lowerCamelCase,	len(lowerCamelCase							)							)

  trainer.log_metrics("""eval""",	lowerCamelCase							)
  trainer.save_metrics("""eval""",	lowerCamelCase							)

 return results


if __name__ == "__main__":
      main()






# Copyright 2021 The HuggingFace Inc. 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 packaging import version

from .. import __version__
from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD
from .doc import (
    add_code_sample_docstrings,
    add_end_docstrings,
    add_start_docstrings,
    add_start_docstrings_to_model_forward,
    copy_func,
    replace_return_docstrings,
)
from .generic import (
    ContextManagers,
    ExplicitEnum,
    ModelOutput,
    PaddingStrategy,
    TensorType,
    add_model_info_to_auto_map,
    cached_property,
    can_return_loss,
    expand_dims,
    find_labels,
    flatten_dict,
    infer_framework,
    is_jax_tensor,
    is_numpy_array,
    is_tensor,
    is_tf_symbolic_tensor,
    is_tf_tensor,
    is_torch_device,
    is_torch_dtype,
    is_torch_tensor,
    reshape,
    squeeze,
    strtobool,
    tensor_size,
    to_numpy,
    to_py_obj,
    transpose,
    working_or_temp_dir,
)
from .hub import (
    CLOUDFRONT_DISTRIB_PREFIX,
    DISABLE_TELEMETRY,
    HF_MODULES_CACHE,
    HUGGINGFACE_CO_PREFIX,
    HUGGINGFACE_CO_RESOLVE_ENDPOINT,
    PYTORCH_PRETRAINED_BERT_CACHE,
    PYTORCH_TRANSFORMERS_CACHE,
    S3_BUCKET_PREFIX,
    TRANSFORMERS_CACHE,
    TRANSFORMERS_DYNAMIC_MODULE_NAME,
    EntryNotFoundError,
    PushToHubMixin,
    RepositoryNotFoundError,
    RevisionNotFoundError,
    cached_file,
    default_cache_path,
    define_sagemaker_information,
    download_url,
    extract_commit_hash,
    get_cached_models,
    get_file_from_repo,
    get_full_repo_name,
    has_file,
    http_user_agent,
    is_offline_mode,
    is_remote_url,
    move_cache,
    send_example_telemetry,
    try_to_load_from_cache,
)
from .import_utils import (
    ENV_VARS_TRUE_AND_AUTO_VALUES,
    ENV_VARS_TRUE_VALUES,
    TORCH_FX_REQUIRED_VERSION,
    USE_JAX,
    USE_TF,
    USE_TORCH,
    DummyObject,
    OptionalDependencyNotAvailable,
    _LazyModule,
    ccl_version,
    direct_transformers_import,
    get_torch_version,
    is_accelerate_available,
    is_apex_available,
    is_bitsandbytes_available,
    is_bsa_available,
    is_coloredlogs_available,
    is_cython_available,
    is_datasets_available,
    is_decord_available,
    is_detectrona_available,
    is_faiss_available,
    is_flax_available,
    is_ftfy_available,
    is_in_notebook,
    is_ipex_available,
    is_jieba_available,
    is_jumanpp_available,
    is_kenlm_available,
    is_keras_nlp_available,
    is_librosa_available,
    is_natten_available,
    is_ninja_available,
    is_onnx_available,
    is_openai_available,
    is_optimum_available,
    is_pandas_available,
    is_peft_available,
    is_phonemizer_available,
    is_protobuf_available,
    is_psutil_available,
    is_pyanvml_available,
    is_pyctcdecode_available,
    is_pytesseract_available,
    is_pytest_available,
    is_pytorch_quantization_available,
    is_rjieba_available,
    is_sacremoses_available,
    is_safetensors_available,
    is_sagemaker_dp_enabled,
    is_sagemaker_mp_enabled,
    is_scipy_available,
    is_sentencepiece_available,
    is_seqio_available,
    is_sklearn_available,
    is_soundfile_availble,
    is_spacy_available,
    is_speech_available,
    is_sudachi_available,
    is_tensorflow_probability_available,
    is_tensorflow_text_available,
    is_tfaonnx_available,
    is_tf_available,
    is_timm_available,
    is_tokenizers_available,
    is_torch_available,
    is_torch_bfaa_available,
    is_torch_bfaa_cpu_available,
    is_torch_bfaa_gpu_available,
    is_torch_compile_available,
    is_torch_cuda_available,
    is_torch_fx_available,
    is_torch_fx_proxy,
    is_torch_mps_available,
    is_torch_neuroncore_available,
    is_torch_tensorrt_fx_available,
    is_torch_tfaa_available,
    is_torch_tpu_available,
    is_torchaudio_available,
    is_torchdistx_available,
    is_torchdynamo_available,
    is_torchvision_available,
    is_training_run_on_sagemaker,
    is_vision_available,
    requires_backends,
    torch_only_method,
)


_lowerCamelCase					   ="""pytorch_model.bin"""
_lowerCamelCase					   ="""pytorch_model.bin.index.json"""
_lowerCamelCase					   ="""adapter_config.json"""
_lowerCamelCase					   ="""adapter_model.bin"""
_lowerCamelCase					   ="""adapter_model.safetensors"""
_lowerCamelCase					   ="""tf_model.h5"""
_lowerCamelCase					   ="""tf_model.h5.index.json"""
_lowerCamelCase					   ="""model.ckpt"""
_lowerCamelCase					   ="""flax_model.msgpack"""
_lowerCamelCase					   ="""flax_model.msgpack.index.json"""
_lowerCamelCase					   ="""model.safetensors"""
_lowerCamelCase					   ="""model.safetensors.index.json"""
_lowerCamelCase					   ="""config.json"""
_lowerCamelCase					   ="""preprocessor_config.json"""
_lowerCamelCase					   =FEATURE_EXTRACTOR_NAME
_lowerCamelCase					   ="""generation_config.json"""
_lowerCamelCase					   ="""modelcard.json"""

_lowerCamelCase					   ="""▁"""
_lowerCamelCase					   =SENTENCEPIECE_UNDERLINE  # Kept for backward compatibility

_lowerCamelCase					   =[
    [[0, 1, 0, 1], [1, 0, 0, 1]]
] * 2  # Needs to have 0s and 1s only since XLM uses it for langs too.
_lowerCamelCase					   =[[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]]
_lowerCamelCase					   =[[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]]





def     _a					(						lowerCamelCase							):
 if version.parse(lowerCamelCase							) < version.parse(lowerCamelCase							):
  if "dev" in min_version:
   lowerCamelCase		:	Optional[int]							=      (
       """This example requires a source install from HuggingFace Transformers (see """
       """`https://huggingface.co/docs/transformers/installation#install-from-source`),"""
   )
  else:
   lowerCamelCase		:	int							=      F'''This example requires a minimum version of {min_version},'''
  error_message += F''' but the version found is {__version__}.\n'''
  raise ImportError(
      error_message
      + """Check out https://github.com/huggingface/transformers/tree/main/examples#important-note for the examples corresponding to other """
      """versions of HuggingFace Transformers."""							)




