





import json
import logging
import os
import random
import sys
from dataclasses import dataclass, field
from typing import Optional

import evaluate
import numpy as np
import torch
from datasets import load_dataset
from huggingface_hub import hf_hub_download
from PIL import Image
from torch import nn
from torchvision import transforms
from torchvision.transforms import functional

import transformers
from transformers import (
    AutoConfig,
    AutoImageProcessor,
    AutoModelForSemanticSegmentation,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
__UpperCamelCase										=  logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("4.31.0")

require_version("datasets>=2.0.0", "To fix: pip install -r examples/pytorch/semantic-segmentation/requirements.txt")







def 				_a	(					_lowerCamelCase						,  _lowerCamelCase						,  _lowerCamelCase=0   )   ->							Tuple:



			"""simple docstring"""


			__snake_case				:			Optional[Any]       			=    (size, size) if isinstance(_lowerCamelCase						,  _lowerCamelCase   ) else size
			__snake_case				:			Optional[int]       			=    img.size
			__snake_case				:			List[str]       			=    size[1] - original_height if original_height < size[1] else 0
			__snake_case				:			str       			=    size[0] - original_width if original_width < size[0] else 0
			__snake_case				:			Optional[int]       			=    functional.pad(_lowerCamelCase						,  (0, 0, pad_width, pad_height)						,  fill=_lowerCamelCase   )
			return img




class    _A   :

		def __init__(      self				:      Dict     ,			__magic_name__				:      List[str] )				->						Optional[Any]:


					"""simple docstring"""

					__snake_case				:			Dict       			=    transforms

		def __call__(      self				:      Tuple     ,			__magic_name__				:      Optional[int]     ,			__magic_name__				:      List[Any] )				->						Optional[Any]:


					"""simple docstring"""

					for t in self.transforms:
								__snake_case				:			Optional[Any]       			=    t(__magic_name__     ,			__magic_name__ )
					return image, target





class    _A   :

		def __init__(      self				:      Tuple )				->						int:


					"""simple docstring"""

					pass

		def __call__(      self				:      List[str]     ,			__magic_name__				:      Any     ,			__magic_name__				:      Optional[Any] )				->						Union[str, Any]:


					"""simple docstring"""

					return image, target





class    _A   :

		def __init__(      self				:      str     ,			__magic_name__				:      List[str] )				->						int:


					"""simple docstring"""

					__snake_case				:			Optional[int]       			=    size

		def __call__(      self				:      Dict     ,			__magic_name__				:      List[Any]     ,			__magic_name__				:      Optional[int] )				->						Any:


					"""simple docstring"""

					__snake_case				:			int       			=    functional.resize(__magic_name__     ,			self.size )
					__snake_case				:			Union[str, Any]       			=    functional.resize(__magic_name__     ,			self.size     ,			interpolation=transforms.InterpolationMode.NEAREST )
					return image, target





class    _A   :

		def __init__(      self				:      Union[str, Any]     ,			__magic_name__				:      Optional[Any]     ,			__magic_name__				:      str=None )				->						List[Any]:


					"""simple docstring"""

					__snake_case				:			Optional[Any]       			=    min_size
					if max_size is None:
								__snake_case				:			List[str]       			=    min_size
					__snake_case				:			Any       			=    max_size

		def __call__(      self				:      List[str]     ,			__magic_name__				:      Tuple     ,			__magic_name__				:      str )				->						List[str]:


					"""simple docstring"""

					__snake_case				:			str       			=    random.randint(self.min_size     ,			self.max_size )
					__snake_case				:			List[Any]       			=    functional.resize(__magic_name__     ,			__magic_name__ )
					__snake_case				:			Tuple       			=    functional.resize(__magic_name__     ,			__magic_name__     ,			interpolation=transforms.InterpolationMode.NEAREST )
					return image, target





class    _A   :

		def __init__(      self				:      Dict     ,			__magic_name__				:      Optional[Any] )				->						Dict:


					"""simple docstring"""

					__snake_case				:			Union[str, Any]       			=    size if isinstance(__magic_name__     ,			__magic_name__ ) else (size, size)

		def __call__(      self				:      Dict     ,			__magic_name__				:      Union[str, Any]     ,			__magic_name__				:      Union[str, Any] )				->						Optional[int]:


					"""simple docstring"""

					__snake_case				:			str       			=    pad_if_smaller(__magic_name__     ,			self.size )
					__snake_case				:			str       			=    pad_if_smaller(__magic_name__     ,			self.size     ,			fill=2_55 )
					__snake_case				:			Dict       			=    transforms.RandomCrop.get_params(__magic_name__     ,			self.size )
					__snake_case				:			List[Any]       			=    functional.crop(__magic_name__     ,			*__magic_name__ )
					__snake_case				:			Union[str, Any]       			=    functional.crop(__magic_name__     ,			*__magic_name__ )
					return image, target





class    _A   :

		def __init__(      self				:      List[Any]     ,			__magic_name__				:      Any )				->						List[str]:


					"""simple docstring"""

					__snake_case				:			Any       			=    flip_prob

		def __call__(      self				:      int     ,			__magic_name__				:      str     ,			__magic_name__				:      Tuple )				->						Optional[Any]:


					"""simple docstring"""

					if random.random() < self.flip_prob:
								__snake_case				:			Union[str, Any]       			=    functional.hflip(__magic_name__ )
								__snake_case				:			str       			=    functional.hflip(__magic_name__ )
					return image, target





class    _A   :

		def __call__(      self				:      Dict     ,			__magic_name__				:      Optional[Any]     ,			__magic_name__				:      str )				->						Optional[Any]:


					"""simple docstring"""

					__snake_case				:			Optional[int]       			=    functional.pil_to_tensor(__magic_name__ )
					__snake_case				:			Optional[Any]       			=    torch.as_tensor(np.array(__magic_name__ )     ,			dtype=torch.intaa )
					return image, target





class    _A   :

		def __init__(      self				:      Any     ,			__magic_name__				:      List[str] )				->						Optional[Any]:


					"""simple docstring"""

					__snake_case				:			Union[str, Any]       			=    dtype

		def __call__(      self				:      Union[str, Any]     ,			__magic_name__				:      Union[str, Any]     ,			__magic_name__				:      Union[str, Any] )				->						int:


					"""simple docstring"""

					__snake_case				:			Any       			=    functional.convert_image_dtype(__magic_name__     ,			self.dtype )
					return image, target





class    _A   :

		def __init__(      self				:      Union[str, Any]     ,			__magic_name__				:      Tuple     ,			__magic_name__				:      Dict )				->						Any:


					"""simple docstring"""

					__snake_case				:			Tuple       			=    mean
					__snake_case				:			Optional[int]       			=    std

		def __call__(      self				:      List[Any]     ,			__magic_name__				:      Any     ,			__magic_name__				:      Optional[int] )				->						int:


					"""simple docstring"""

					__snake_case				:			Tuple       			=    functional.normalize(__magic_name__     ,			mean=self.mean     ,			std=self.std )
					return image, target





class    _A   :

		def __call__(      self				:      Optional[int]     ,			__magic_name__				:      List[str]     ,			__magic_name__				:      Tuple )				->						Union[str, Any]:


					"""simple docstring"""

					if not isinstance(__magic_name__     ,			np.ndarray ):
								__snake_case				:			int       			=    np.array(__magic_name__ ).astype(np.uinta )
					# avoid using underflow conversion
					__snake_case				:			Tuple       			=    2_55
					__snake_case				:			List[Any]       			=    target - 1
					__snake_case				:			Union[str, Any]       			=    2_55

					__snake_case				:			Optional[int]       			=    Image.fromarray(__magic_name__ )
					return image, target





@dataclass
class    _A   :
		lowercase__:      Optional[str]							    =      field(
		    default='''segments/sidewalk-semantic'''	,				metadata={
		        '''help''': '''Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub).'''
		    }	,				)
		lowercase__:      Optional[str]							    =      field(
		    default=__lowercase	,				metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''}		)
		lowercase__:      Optional[float]							    =      field(
		    default=0.1_5	,				metadata={'''help''': '''Percent to split off of train for validation.'''}		)
		lowercase__:      Optional[int]							    =      field(
		    default=__lowercase	,				metadata={
		        '''help''': (
		            '''For debugging purposes or quicker training, truncate the number of training examples to this '''
		            '''value if set.'''
		        )
		    }	,				)
		lowercase__:      Optional[int]							    =      field(
		    default=__lowercase	,				metadata={
		        '''help''': (
		            '''For debugging purposes or quicker training, truncate the number of evaluation examples to this '''
		            '''value if set.'''
		        )
		    }	,				)
		lowercase__:      Optional[bool]							    =      field(
		    default=__lowercase	,				metadata={'''help''': '''Whether or not to reduce all labels by 1 and replace background by 255.'''}	,				)

		def   lowercase__    (      self				:      List[Any] )				->						List[Any]:


					"""simple docstring"""

					if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None):
								raise ValueError(
								    """You must specify either a dataset name from the hub or a train and/or validation directory.""" )





@dataclass
class    _A   :
		lowercase__:      str							    =      field(
		    default='''nvidia/mit-b0'''	,				metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}	,				)
		lowercase__:      Optional[str]							    =      field(
		    default=__lowercase	,				metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''}		)
		lowercase__:      Optional[str]							    =      field(
		    default=__lowercase	,				metadata={'''help''': '''Where do you want to store the pretrained models downloaded from s3'''}		)
		lowercase__:      str							    =      field(
		    default='''main'''	,				metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''}	,				)
		lowercase__:      str							    =      field(default=__lowercase	,				metadata={'''help''': '''Name or path of preprocessor config.'''}		)
		lowercase__:      bool							    =      field(
		    default=__lowercase	,				metadata={
		        '''help''': (
		            '''Will use the token generated when running `huggingface-cli login` (necessary to use this script '''
		            '''with private models).'''
		        )
		    }	,				)







def 				_a	(					)   ->							Dict:



			"""simple docstring"""


			__snake_case				:			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.
						__snake_case				:			Tuple       			=    parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]   )   )
			else:
						__snake_case				:			Any       			=    parser.parse_args_into_dataclasses()

			# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
			# information sent is the one passed as arguments along with your Python/PyTorch versions.
			send_example_telemetry("""run_semantic_segmentation"""						,  _lowerCamelCase						,  _lowerCamelCase   )

			# 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   )]						,  )

			if training_args.should_log:
						# The default of training_args.log_level is passive, so we set log level at info here to have that default.
						transformers.utils.logging.set_verbosity_info()

			__snake_case				:			int       			=    training_args.get_process_log_level()
			logger.setLevel(_lowerCamelCase   )
			transformers.utils.logging.set_verbosity(_lowerCamelCase   )
			transformers.utils.logging.enable_default_handler()
			transformers.utils.logging.enable_explicit_format()

			# 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}'''   )
			logger.info(F'''Training/evaluation parameters {training_args}'''   )

			# Detecting last checkpoint.
			__snake_case				:			List[str]       			=    None
			if os.path.isdir(training_args.output_dir   ) and training_args.do_train and not training_args.overwrite_output_dir:
						__snake_case				:			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 and training_args.resume_from_checkpoint is 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."""   )

    # Load dataset
    # In distributed training, the load_dataset function guarantees that only one local process can concurrently
    # download the dataset.
    # TODO support datasets from local folders
			__snake_case				:			List[Any]       			=    load_dataset(data_args.dataset_name						,  cache_dir=model_args.cache_dir   )

			# Rename column names to standardized names (only "image" and "label" need to be present)
			if "pixel_values" in dataset["train"].column_names:
						__snake_case				:			str       			=    dataset.rename_columns({"""pixel_values""": """image"""}   )
			if "annotation" in dataset["train"].column_names:
						__snake_case				:			List[Any]       			=    dataset.rename_columns({"""annotation""": """label"""}   )

			# If we don't have a validation split, split off a percentage of train as validation.
			__snake_case				:			str       			=    None if """validation""" in dataset.keys() else data_args.train_val_split
			if isinstance(data_args.train_val_split						,  _lowerCamelCase   ) and data_args.train_val_split > 0.0:
						__snake_case				:			Dict       			=    dataset["""train"""].train_test_split(data_args.train_val_split   )
						__snake_case				:			Optional[Any]       			=    split["""train"""]
						__snake_case				:			Union[str, Any]       			=    split["""test"""]

			# Prepare label mappings.
			# We'll include these in the model's config to get human readable labels in the Inference API.
			if data_args.dataset_name == "scene_parse_150":
						__snake_case				:			int       			=    """huggingface/label-files"""
						__snake_case				:			Dict       			=    """ade20k-id2label.json"""
			else:
						__snake_case				:			Union[str, Any]       			=    data_args.dataset_name
						__snake_case				:			Tuple       			=    """id2label.json"""
			__snake_case				:			Union[str, Any]       			=    json.load(open(hf_hub_download(_lowerCamelCase						,  _lowerCamelCase						,  repo_type="""dataset"""   )						,  """r"""   )   )
			__snake_case				:			Any       			=    {int(_lowerCamelCase   ): v for k, v in idalabel.items()}
			__snake_case				:			Optional[Any]       			=    {v: str(_lowerCamelCase   ) for k, v in idalabel.items()}

			# Load the mean IoU metric from the datasets package
			__snake_case				:			List[str]       			=    evaluate.load("""mean_iou"""   )

			# Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
			# predictions and label_ids field) and has to return a dictionary string to float.
			@torch.no_grad()
			def compute_metrics(_lowerCamelCase   ):
						__snake_case				:			Any       			=    eval_pred
						__snake_case				:			int       			=    torch.from_numpy(_lowerCamelCase   )
						# scale the logits to the size of the label
						__snake_case				:			str       			=    nn.functional.interpolate(
						    _lowerCamelCase						,  size=labels.shape[-2:]						,  mode="""bilinear"""						,  align_corners=_lowerCamelCase						,  ).argmax(dim=1   )

						__snake_case				:			Union[str, Any]       			=    logits_tensor.detach().cpu().numpy()
						__snake_case				:			int       			=    metric.compute(
						    predictions=_lowerCamelCase						,  references=_lowerCamelCase						,  num_labels=len(_lowerCamelCase   )						,  ignore_index=0						,  reduce_labels=image_processor.do_reduce_labels						,  )
						# add per category metrics as individual key-value pairs
						__snake_case				:			int       			=    metrics.pop("""per_category_accuracy"""   ).tolist()
						__snake_case				:			List[str]       			=    metrics.pop("""per_category_iou"""   ).tolist()

						metrics.update({F'''accuracy_{idalabel[i]}''': v for i, v in enumerate(_lowerCamelCase   )}   )
						metrics.update({F'''iou_{idalabel[i]}''': v for i, v in enumerate(_lowerCamelCase   )}   )

						return metrics

			__snake_case				:			Union[str, Any]       			=    AutoConfig.from_pretrained(
			    model_args.config_name or model_args.model_name_or_path						,  labelaid=_lowerCamelCase						,  idalabel=_lowerCamelCase						,  cache_dir=model_args.cache_dir						,  revision=model_args.model_revision						,  use_auth_token=True if model_args.use_auth_token else None						,  )
			__snake_case				:			str       			=    AutoModelForSemanticSegmentation.from_pretrained(
			    model_args.model_name_or_path						,  from_tf=bool(""".ckpt""" in model_args.model_name_or_path   )						,  config=_lowerCamelCase						,  cache_dir=model_args.cache_dir						,  revision=model_args.model_revision						,  use_auth_token=True if model_args.use_auth_token else None						,  )
			__snake_case				:			str       			=    AutoImageProcessor.from_pretrained(
			    model_args.image_processor_name or model_args.model_name_or_path						,  cache_dir=model_args.cache_dir						,  revision=model_args.model_revision						,  use_auth_token=True if model_args.use_auth_token else None						,  )

			# Define torchvision transforms to be applied to each image + target.
			# Not that straightforward in torchvision: https://github.com/pytorch/vision/issues/9
			# Currently based on official torchvision references: https://github.com/pytorch/vision/blob/main/references/segmentation/transforms.py
			if "shortest_edge" in image_processor.size:
						# We instead set the target size as (shortest_edge, shortest_edge) to here to ensure all images are batchable.
						__snake_case				:			int       			=    (image_processor.size["""shortest_edge"""], image_processor.size["""shortest_edge"""])
			else:
						__snake_case				:			Union[str, Any]       			=    (image_processor.size["""height"""], image_processor.size["""width"""])
			__snake_case				:			str       			=    Compose(
			    [
			        ReduceLabels() if data_args.reduce_labels else Identity(),
			        RandomCrop(size=_lowerCamelCase   ),
			        RandomHorizontalFlip(flip_prob=0.5   ),
			        PILToTensor(),
			        ConvertImageDtype(torch.float   ),
			        Normalize(mean=image_processor.image_mean						,  std=image_processor.image_std   ),
			    ]   )
			# Define torchvision transform to be applied to each image.
			# jitter = ColorJitter(brightness=0.25, contrast=0.25, saturation=0.25, hue=0.1)
			__snake_case				:			Tuple       			=    Compose(
			    [
			        ReduceLabels() if data_args.reduce_labels else Identity(),
			        Resize(size=_lowerCamelCase   ),
			        PILToTensor(),
			        ConvertImageDtype(torch.float   ),
			        Normalize(mean=image_processor.image_mean						,  std=image_processor.image_std   ),
			    ]   )

			def preprocess_train(_lowerCamelCase   ):
						__snake_case				:			str       			=    []
						__snake_case				:			Tuple       			=    []
						for image, target in zip(example_batch["""image"""]						,  example_batch["""label"""]   ):
									__snake_case				:			List[Any]       			=    train_transforms(image.convert("""RGB"""   )						,  _lowerCamelCase   )
									pixel_values.append(_lowerCamelCase   )
									labels.append(_lowerCamelCase   )

						__snake_case				:			Dict       			=    {}
						__snake_case				:			Tuple       			=    torch.stack(_lowerCamelCase   )
						__snake_case				:			int       			=    torch.stack(_lowerCamelCase   )

						return encoding

			def preprocess_val(_lowerCamelCase   ):
						__snake_case				:			Tuple       			=    []
						__snake_case				:			Optional[int]       			=    []
						for image, target in zip(example_batch["""image"""]						,  example_batch["""label"""]   ):
									__snake_case				:			Tuple       			=    val_transforms(image.convert("""RGB"""   )						,  _lowerCamelCase   )
									pixel_values.append(_lowerCamelCase   )
									labels.append(_lowerCamelCase   )

						__snake_case				:			Optional[Any]       			=    {}
						__snake_case				:			int       			=    torch.stack(_lowerCamelCase   )
						__snake_case				:			List[Any]       			=    torch.stack(_lowerCamelCase   )

						return encoding

			if training_args.do_train:
						if "train" not in dataset:
									raise ValueError("""--do_train requires a train dataset"""   )
						if data_args.max_train_samples is not None:
									__snake_case				:			str       			=    (
									    dataset["""train"""].shuffle(seed=training_args.seed   ).select(range(data_args.max_train_samples   )   )
									)
						# Set the training transforms
						dataset["train"].set_transform(_lowerCamelCase   )

			if training_args.do_eval:
						if "validation" not in dataset:
									raise ValueError("""--do_eval requires a validation dataset"""   )
						if data_args.max_eval_samples is not None:
									__snake_case				:			Dict       			=    (
									    dataset["""validation"""].shuffle(seed=training_args.seed   ).select(range(data_args.max_eval_samples   )   )
									)
						# Set the validation transforms
						dataset["validation"].set_transform(_lowerCamelCase   )

			# Initalize our trainer
			__snake_case				:			Optional[int]       			=    Trainer(
			    model=_lowerCamelCase						,  args=_lowerCamelCase						,  train_dataset=dataset["""train"""] if training_args.do_train else None						,  eval_dataset=dataset["""validation"""] if training_args.do_eval else None						,  compute_metrics=_lowerCamelCase						,  tokenizer=_lowerCamelCase						,  data_collator=_lowerCamelCase						,  )

			# Training
			if training_args.do_train:
						__snake_case				:			Optional[Any]       			=    None
						if training_args.resume_from_checkpoint is not None:
									__snake_case				:			Tuple       			=    training_args.resume_from_checkpoint
						elif last_checkpoint is not None:
									__snake_case				:			Optional[int]       			=    last_checkpoint
						__snake_case				:			Dict       			=    trainer.train(resume_from_checkpoint=_lowerCamelCase   )
						trainer.save_model()
						trainer.log_metrics("""train"""						,  train_result.metrics   )
						trainer.save_metrics("""train"""						,  train_result.metrics   )
						trainer.save_state()

			# Evaluation
			if training_args.do_eval:
						__snake_case				:			Optional[int]       			=    trainer.evaluate()
						trainer.log_metrics("""eval"""						,  _lowerCamelCase   )
						trainer.save_metrics("""eval"""						,  _lowerCamelCase   )

			# Write model card and (optionally) push to hub
			__snake_case				:			Optional[Any]       			=    {
			    """finetuned_from""": model_args.model_name_or_path,
			    """dataset""": data_args.dataset_name,
			    """tags""": ["""image-segmentation""", """vision"""],
			}
			if training_args.push_to_hub:
						trainer.push_to_hub(**_lowerCamelCase   )
			else:
						trainer.create_model_card(**_lowerCamelCase   )


if __name__ == "__main__":
	main()









'''simple docstring'''






import os
import tempfile
import unittest
from typing import List

from transformers.models.esm.tokenization_esm import VOCAB_FILES_NAMES, EsmTokenizer
from transformers.testing_utils import require_tokenizers
from transformers.tokenization_utils import PreTrainedTokenizer
from transformers.tokenization_utils_base import PreTrainedTokenizerBase




@require_tokenizers
class    _A   (				unittest.TestCase		):
		lowercase__:      Tuple							    =      EsmTokenizer

		def   lowercase__    (      self				:      Tuple )				->						Optional[int]:


					"""simple docstring"""

					super().setUp()
					__snake_case				:			str       			=    tempfile.mkdtemp()
					# fmt: off
					__snake_case				:			List[str]       			=    ["<cls>", "<pad>", "<eos>", "<unk>", "L", "A", "G", "V", "S", "E", "R", "T", "I", "D", "P", "K", "Q", "N", "F", "Y", "M", "H", "W", "C", "X", "B", "U", "Z", "O", ".", "-", "<null_1>", "<mask>"]  # noqa: E501
					# fmt: on
					__snake_case				:			Tuple       			=    os.path.join(self.tmpdirname     ,			VOCAB_FILES_NAMES["""vocab_file"""] )
					with open(self.vocab_file     ,			"""w"""     ,			encoding="""utf-8""" ) as vocab_writer:
								vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) )

		def   lowercase__    (      self				:      List[Any]     ,			**__magic_name__				:      Tuple )				->						List[PreTrainedTokenizerBase]:


					"""simple docstring"""

					return [self.get_tokenizer(**__magic_name__ )]

		def   lowercase__    (      self				:      int     ,			**__magic_name__				:      Dict )				->						PreTrainedTokenizer:


					"""simple docstring"""

					return self.tokenizer_class.from_pretrained(self.tmpdirname     ,			**__magic_name__ )

		def   lowercase__    (      self				:      Union[str, Any] )				->						Dict:


					"""simple docstring"""

					__snake_case				:			Dict       			=    self.tokenizer_class(self.vocab_file )

					__snake_case				:			Optional[int]       			=    tokenizer.tokenize("""LAGVS""" )
					self.assertListEqual(__magic_name__     ,			["""L""", """A""", """G""", """V""", """S"""] )
					self.assertListEqual(tokenizer.convert_tokens_to_ids(__magic_name__ )     ,			[4, 5, 6, 7, 8] )

		def   lowercase__    (      self				:      List[str] )				->						Optional[Any]:


					"""simple docstring"""

					__snake_case				:			str       			=    self.tokenizer_class(self.vocab_file )

					__snake_case				:			Optional[int]       			=    """LAGVS"""
					self.assertListEqual(tokenizer.encode(__magic_name__ )     ,			[0, 4, 5, 6, 7, 8, 2] )

		def   lowercase__    (      self				:      str )				->						Optional[Any]:


					"""simple docstring"""

					__snake_case				:			Dict       			=    self.tokenizer_class(self.vocab_file )

					__snake_case				:			Tuple       			=    ["""LAGVS""", """WCB"""]
					__snake_case				:			Dict       			=    tokenizer(__magic_name__     ,			padding=__magic_name__ )["""input_ids"""]

					self.assertListEqual(__magic_name__     ,			[[0, 4, 5, 6, 7, 8, 2], [0, 22, 23, 25, 2]] )

		def   lowercase__    (      self				:      str )				->						List[Any]:


					"""simple docstring"""

					__snake_case				:			int       			=    self.tokenizer_class(self.vocab_file )

					__snake_case				:			List[Any]       			=    ["""LAGVS""", """WCB"""]
					__snake_case				:			Any       			=    tokenizer(__magic_name__     ,			padding=__magic_name__ )["""input_ids"""]

					self.assertListEqual(__magic_name__     ,			[[0, 4, 5, 6, 7, 8, 2], [0, 22, 23, 25, 2, 1, 1]] )

		def   lowercase__    (      self				:      List[str] )				->						Tuple:


					"""simple docstring"""

					__snake_case				:			Any       			=    self.get_tokenizers(fast=__magic_name__ )
					for tokenizer in tokenizers:
								with self.subTest(f'''{tokenizer.__class__.__name__}''' ):
											__snake_case				:			int       			=    """<unk>"""
											__snake_case				:			Optional[Any]       			=    """<mask>"""

											__snake_case				:			Tuple       			=    tokenizer.tokenize(__magic_name__ )
											__snake_case				:			List[Any]       			=    tokenizer.tokenize(__magic_name__ )

											self.assertEqual(len(__magic_name__ )     ,			1 )
											self.assertEqual(len(__magic_name__ )     ,			1 )
											self.assertEqual(token_a[0]     ,			__magic_name__ )
											self.assertEqual(token_a[0]     ,			__magic_name__ )


