





"""simple docstring"""
import inspect
import unittest

import numpy as np

from tests.test_modeling_common import floats_tensor
from transformers import MaskaFormerConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch

  from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel

  if is_vision_available():
    from transformers import MaskaFormerImageProcessor

if is_vision_available():
  from PIL import Image






class    _SCREAMING_SNAKE_CASE:




       def __init__(		self						,SCREAMING_SNAKE_CASE__						,SCREAMING_SNAKE_CASE__=2						,SCREAMING_SNAKE_CASE__=True						,SCREAMING_SNAKE_CASE__=False						,SCREAMING_SNAKE_CASE__=10						,SCREAMING_SNAKE_CASE__=3						,SCREAMING_SNAKE_CASE__=32 * 8						,SCREAMING_SNAKE_CASE__=32 * 8						,SCREAMING_SNAKE_CASE__=4						,SCREAMING_SNAKE_CASE__=64						,)     -> str:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE  :List[str]													=    parent
             __SCREAMING_SNAKE_CASE  :Dict													=    batch_size
             __SCREAMING_SNAKE_CASE  :List[Any]													=    is_training
             __SCREAMING_SNAKE_CASE  :str													=    use_auxiliary_loss
             __SCREAMING_SNAKE_CASE  :Dict													=    num_queries
             __SCREAMING_SNAKE_CASE  :Optional[int]													=    num_channels
             __SCREAMING_SNAKE_CASE  :Tuple													=    min_size
             __SCREAMING_SNAKE_CASE  :Tuple													=    max_size
             __SCREAMING_SNAKE_CASE  :List[str]													=    num_labels
             __SCREAMING_SNAKE_CASE  :Union[str, Any]													=    hidden_dim
             __SCREAMING_SNAKE_CASE  :Union[str, Any]													=    hidden_dim




       def        _UpperCamelCase	(		self				)     -> Optional[Any]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE  :int													=    floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]				).to(
                 A_				)

             __SCREAMING_SNAKE_CASE  :Optional[int]													=    torch.ones([self.batch_size, self.min_size, self.max_size]						,device=A_				)

             __SCREAMING_SNAKE_CASE  :Tuple													=    (
                 torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size]						,device=A_				) > 0.5
             ).float()
             __SCREAMING_SNAKE_CASE  :Dict													=    (torch.rand((self.batch_size, self.num_labels)						,device=A_				) > 0.5).long()

             __SCREAMING_SNAKE_CASE  :Optional[Any]													=    self.get_config()
             return config, pixel_values, pixel_mask, mask_labels, class_labels




       def        _UpperCamelCase	(		self				)     -> List[str]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE  :int													=    MaskaFormerConfig(
                 hidden_size=self.hidden_dim						,)
             __SCREAMING_SNAKE_CASE  :Dict													=    self.num_queries
             __SCREAMING_SNAKE_CASE  :str													=    self.num_labels

             __SCREAMING_SNAKE_CASE  :Optional[Any]													=    [1, 1, 1, 1]
             __SCREAMING_SNAKE_CASE  :Union[str, Any]													=    self.num_channels

             __SCREAMING_SNAKE_CASE  :Union[str, Any]													=    64
             __SCREAMING_SNAKE_CASE  :int													=    1_28
             __SCREAMING_SNAKE_CASE  :Tuple													=    self.hidden_dim
             __SCREAMING_SNAKE_CASE  :List[Any]													=    self.hidden_dim
             __SCREAMING_SNAKE_CASE  :Optional[int]													=    self.hidden_dim
             return config




       def        _UpperCamelCase	(		self				)     -> List[str]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE							,__SCREAMING_SNAKE_CASE							,__SCREAMING_SNAKE_CASE							,__SCREAMING_SNAKE_CASE							,__SCREAMING_SNAKE_CASE  :int													=    self.prepare_config_and_inputs()
             __SCREAMING_SNAKE_CASE  :List[Any]													=    {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask}
             return config, inputs_dict




       def        _UpperCamelCase	(		self						,SCREAMING_SNAKE_CASE__						,SCREAMING_SNAKE_CASE__				)     -> List[str]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE  :str													=    output.encoder_hidden_states
             __SCREAMING_SNAKE_CASE  :List[str]													=    output.pixel_decoder_hidden_states
             __SCREAMING_SNAKE_CASE  :Optional[Any]													=    output.transformer_decoder_hidden_states

             self.parent.assertTrue(len(A_				)						,len(config.backbone_config.depths				)				)
             self.parent.assertTrue(len(A_				)						,len(config.backbone_config.depths				)				)
             self.parent.assertTrue(len(A_				)						,config.decoder_layers				)




       def        _UpperCamelCase	(		self						,SCREAMING_SNAKE_CASE__						,SCREAMING_SNAKE_CASE__						,SCREAMING_SNAKE_CASE__						,SCREAMING_SNAKE_CASE__=False				)     -> List[Any]:





             """simple docstring"""






             with torch.no_grad():
                   __SCREAMING_SNAKE_CASE  :int													=    MaskaFormerModel(config=A_				)
                   model.to(A_				)
                   model.eval()

                   __SCREAMING_SNAKE_CASE  :List[Any]													=    model(pixel_values=A_						,pixel_mask=A_				)
                   __SCREAMING_SNAKE_CASE  :Optional[int]													=    model(A_						,output_hidden_states=A_				)

             self.parent.assertEqual(
                 output.transformer_decoder_last_hidden_state.shape						,(self.batch_size, self.num_queries, self.hidden_dim)						,)
             # let's ensure the other two hidden state exists
             self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None				)
             self.parent.assertTrue(output.encoder_last_hidden_state is not None				)

             if output_hidden_states:
                   self.check_output_hidden_state(A_						,A_				)




       def        _UpperCamelCase	(		self						,SCREAMING_SNAKE_CASE__						,SCREAMING_SNAKE_CASE__						,SCREAMING_SNAKE_CASE__						,SCREAMING_SNAKE_CASE__						,SCREAMING_SNAKE_CASE__				)     -> Optional[Any]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE  :Optional[Any]													=    MaskaFormerForUniversalSegmentation(config=A_				)
             model.to(A_				)
             model.eval()

             def comm_check_on_output(SCREAMING_SNAKE_CASE__				):
                   # let's still check that all the required stuff is there
                   self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None				)
                   self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None				)
                   self.parent.assertTrue(result.encoder_last_hidden_state is not None				)
                   # okay, now we need to check the logits shape
                   # due to the encoder compression, masks have a //4 spatial size
                   self.parent.assertEqual(
                       result.masks_queries_logits.shape						,(self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4)						,)
                   # + 1 for null class
                   self.parent.assertEqual(
                       result.class_queries_logits.shape						,(self.batch_size, self.num_queries, self.num_labels + 1)				)

             with torch.no_grad():
                   __SCREAMING_SNAKE_CASE  :Optional[Any]													=    model(pixel_values=A_						,pixel_mask=A_				)
                   __SCREAMING_SNAKE_CASE  :List[Any]													=    model(A_				)

                   comm_check_on_output(A_				)

                   __SCREAMING_SNAKE_CASE  :Union[str, Any]													=    model(
                       pixel_values=A_						,pixel_mask=A_						,mask_labels=A_						,class_labels=A_				)

             comm_check_on_output(A_				)

             self.parent.assertTrue(result.loss is not None				)
             self.parent.assertEqual(result.loss.shape						,torch.Size([1]				)				)






@require_torch
class    _SCREAMING_SNAKE_CASE(  _a       ,      _a       ,      unittest.TestCase    ):
       SCREAMING_SNAKE_CASE_  : Optional[Any]      		=    (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else ()
       SCREAMING_SNAKE_CASE_  : Optional[int]      		=    {"""feature-extraction""": MaskaFormerModel} if is_torch_available() else {}

       SCREAMING_SNAKE_CASE_  : List[Any]      		=    False
       SCREAMING_SNAKE_CASE_  : Any      		=    False
       SCREAMING_SNAKE_CASE_  : str      		=    False
       SCREAMING_SNAKE_CASE_  : Union[str, Any]      		=    False




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





             """simple docstring"""






             __SCREAMING_SNAKE_CASE  :Dict													=    MaskaFormerModelTester(self				)
             __SCREAMING_SNAKE_CASE  :List[str]													=    ConfigTester(self						,config_class=A_						,has_text_modality=A_				)




       def        _UpperCamelCase	(		self				)     -> Optional[Any]:





             """simple docstring"""






             self.config_tester.run_common_tests()




       def        _UpperCamelCase	(		self				)     -> List[str]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE							,__SCREAMING_SNAKE_CASE  :Dict													=    self.model_tester.prepare_config_and_inputs_for_common()
             self.model_tester.create_and_check_maskaformer_model(A_						,**A_						,output_hidden_states=A_				)




       def        _UpperCamelCase	(		self				)     -> Any:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE  :Optional[int]													=    self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*A_				)




       @unittest.skip(reason='''Mask2Former does not use inputs_embeds'''				)
       def        _UpperCamelCase	(		self				)     -> int:





             """simple docstring"""






             pass




       @unittest.skip(reason='''Mask2Former does not have a get_input_embeddings method'''				)
       def        _UpperCamelCase	(		self				)     -> List[Any]:





             """simple docstring"""






             pass




       @unittest.skip(reason='''Mask2Former is not a generative model'''				)
       def        _UpperCamelCase	(		self				)     -> str:





             """simple docstring"""






             pass




       @unittest.skip(reason='''Mask2Former does not use token embeddings'''				)
       def        _UpperCamelCase	(		self				)     -> str:





             """simple docstring"""






             pass




       @require_torch_multi_gpu
       @unittest.skip(
           reason='''Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`'''				)
       def        _UpperCamelCase	(		self				)     -> List[Any]:





             """simple docstring"""






             pass




       @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''				)
       def        _UpperCamelCase	(		self				)     -> Tuple:





             """simple docstring"""






             pass




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





             """simple docstring"""






             __SCREAMING_SNAKE_CASE							,__SCREAMING_SNAKE_CASE  :str													=    self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                   __SCREAMING_SNAKE_CASE  :List[str]													=    model_class(A_				)
                   __SCREAMING_SNAKE_CASE  :Optional[int]													=    inspect.signature(model.forward				)
                   # signature.parameters is an OrderedDict => so arg_names order is deterministic
                   __SCREAMING_SNAKE_CASE  :str													=    [*signature.parameters.keys()]

                   __SCREAMING_SNAKE_CASE  :Optional[int]													=    ['''pixel_values''']
                   self.assertListEqual(arg_names[:1]						,A_				)




       @slow
       def        _UpperCamelCase	(		self				)     -> Optional[int]:





             """simple docstring"""






             for model_name in ["facebook/mask2former-swin-small-coco-instance"]:
                   __SCREAMING_SNAKE_CASE  :Dict													=    MaskaFormerModel.from_pretrained(A_				)
                   self.assertIsNotNone(A_				)




       def        _UpperCamelCase	(		self				)     -> List[str]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE  :Optional[Any]													=    (self.model_tester.min_size,) * 2
             __SCREAMING_SNAKE_CASE  :List[Any]													=    {
                 '''pixel_values''': torch.randn((2, 3, *size)						,device=A_				),
                 '''mask_labels''': torch.randn((2, 10, *size)						,device=A_				),
                 '''class_labels''': torch.zeros(2						,10						,device=A_				).long(),
             }
             __SCREAMING_SNAKE_CASE  :List[Any]													=    self.model_tester.get_config()

             __SCREAMING_SNAKE_CASE  :Tuple													=    MaskaFormerForUniversalSegmentation(A_				).to(A_				)
             __SCREAMING_SNAKE_CASE  :List[str]													=    model(**A_				)
             self.assertTrue(outputs.loss is not None				)




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





             """simple docstring"""






             __SCREAMING_SNAKE_CASE							,__SCREAMING_SNAKE_CASE  :int													=    self.model_tester.prepare_config_and_inputs_for_common()
             self.model_tester.create_and_check_maskaformer_model(A_						,**A_						,output_hidden_states=A_				)




       def        _UpperCamelCase	(		self				)     -> List[str]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE							,__SCREAMING_SNAKE_CASE  :int													=    self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                   __SCREAMING_SNAKE_CASE  :int													=    model_class(A_				).to(A_				)
                   __SCREAMING_SNAKE_CASE  :Tuple													=    model(**A_						,output_attentions=A_				)
                   self.assertTrue(outputs.attentions is not None				)




       def        _UpperCamelCase	(		self				)     -> Any:





             """simple docstring"""






             if not self.model_tester.is_training:
                   return

             __SCREAMING_SNAKE_CASE  :int													=    self.all_model_classes[1]
             __SCREAMING_SNAKE_CASE							,__SCREAMING_SNAKE_CASE							,__SCREAMING_SNAKE_CASE							,__SCREAMING_SNAKE_CASE							,__SCREAMING_SNAKE_CASE  :Union[str, Any]													=    self.model_tester.prepare_config_and_inputs()

             __SCREAMING_SNAKE_CASE  :str													=    model_class(A_				)
             model.to(A_				)
             model.train()

             __SCREAMING_SNAKE_CASE  :Optional[int]													=    model(A_						,mask_labels=A_						,class_labels=A_				).loss
             loss.backward()




       def        _UpperCamelCase	(		self				)     -> str:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE  :int													=    self.all_model_classes[1]
             __SCREAMING_SNAKE_CASE							,__SCREAMING_SNAKE_CASE							,__SCREAMING_SNAKE_CASE							,__SCREAMING_SNAKE_CASE							,__SCREAMING_SNAKE_CASE  :Optional[Any]													=    self.model_tester.prepare_config_and_inputs()
             __SCREAMING_SNAKE_CASE  :Tuple													=    True
             __SCREAMING_SNAKE_CASE  :Union[str, Any]													=    True

             __SCREAMING_SNAKE_CASE  :Any													=    model_class(A_				).to(A_				)
             model.train()

             __SCREAMING_SNAKE_CASE  :Optional[Any]													=    model(A_						,mask_labels=A_						,class_labels=A_				)

             __SCREAMING_SNAKE_CASE  :int													=    outputs.encoder_hidden_states[0]
             encoder_hidden_states.retain_grad()

             __SCREAMING_SNAKE_CASE  :List[Any]													=    outputs.pixel_decoder_hidden_states[0]
             pixel_decoder_hidden_states.retain_grad()

             __SCREAMING_SNAKE_CASE  :Optional[Any]													=    outputs.transformer_decoder_hidden_states[0]
             transformer_decoder_hidden_states.retain_grad()

             __SCREAMING_SNAKE_CASE  :Union[str, Any]													=    outputs.attentions[0]
             attentions.retain_grad()

             outputs.loss.backward(retain_graph=A_				)

             self.assertIsNotNone(encoder_hidden_states.grad				)
             self.assertIsNotNone(pixel_decoder_hidden_states.grad				)
             self.assertIsNotNone(transformer_decoder_hidden_states.grad				)
             self.assertIsNotNone(attentions.grad				)




lowerCamelCase_        =						1e-4



def 	__lowerCamelCase  (				)     -> str:
      __SCREAMING_SNAKE_CASE  :List[Any]													=    Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''				)
      return image







@require_vision
@slow
class    _SCREAMING_SNAKE_CASE(  unittest.TestCase    ):




       @cached_property
       def        _UpperCamelCase	(		self				)     -> str:





             """simple docstring"""






             return "facebook/mask2former-swin-small-coco-instance"




       @cached_property
       def        _UpperCamelCase	(		self				)     -> int:





             """simple docstring"""






             return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints				) if is_vision_available() else None




       def        _UpperCamelCase	(		self				)     -> Optional[int]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE  :Dict													=    MaskaFormerModel.from_pretrained(self.model_checkpoints				).to(A_				)
             __SCREAMING_SNAKE_CASE  :int													=    self.default_image_processor
             __SCREAMING_SNAKE_CASE  :Any													=    prepare_img()
             __SCREAMING_SNAKE_CASE  :List[str]													=    image_processor(A_						,return_tensors='''pt'''				).to(A_				)
             __SCREAMING_SNAKE_CASE  :Dict													=    inputs['''pixel_values'''].shape
             # check size is divisible by 32
             self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0				)
             # check size
             self.assertEqual(A_						,(1, 3, 3_84, 3_84)				)

             with torch.no_grad():
                   __SCREAMING_SNAKE_CASE  :int													=    model(**A_				)

             __SCREAMING_SNAKE_CASE  :Union[str, Any]													=    torch.tensor(
                 [[-0.2_7_9_0, -1.0_7_1_7, -1.1_6_6_8], [-0.5_1_2_8, -0.3_1_2_8, -0.4_9_8_7], [-0.5_8_3_2, 0.1_9_7_1, -0.0_1_9_7]]				).to(A_				)
             self.assertTrue(
                 torch.allclose(
                     outputs.encoder_last_hidden_state[0, 0, :3, :3]						,A_						,atol=A_				)				)

             __SCREAMING_SNAKE_CASE  :int													=    torch.tensor(
                 [[0.8_9_7_3, 1.1_8_4_7, 1.1_7_7_6], [1.1_9_3_4, 1.5_0_4_0, 1.5_1_2_8], [1.1_1_5_3, 1.4_4_8_6, 1.4_9_5_1]]				).to(A_				)
             self.assertTrue(
                 torch.allclose(
                     outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]						,A_						,atol=A_				)				)

             __SCREAMING_SNAKE_CASE  :int													=    torch.tensor(
                 [[2.1_1_5_2, 1.7_0_0_0, -0.8_6_0_3], [1.5_8_0_8, 1.8_0_0_4, -0.9_3_5_3], [1.6_0_4_3, 1.7_4_9_5, -0.5_9_9_9]]				).to(A_				)
             self.assertTrue(
                 torch.allclose(
                     outputs.transformer_decoder_last_hidden_state[0, :3, :3]						,A_						,atol=A_				)				)




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





             """simple docstring"""






             __SCREAMING_SNAKE_CASE  :Optional[int]													=    MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints				).to(A_				).eval()
             __SCREAMING_SNAKE_CASE  :List[Any]													=    self.default_image_processor
             __SCREAMING_SNAKE_CASE  :List[Any]													=    prepare_img()
             __SCREAMING_SNAKE_CASE  :List[str]													=    image_processor(A_						,return_tensors='''pt'''				).to(A_				)
             __SCREAMING_SNAKE_CASE  :Optional[int]													=    inputs['''pixel_values'''].shape
             # check size is divisible by 32
             self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0				)
             # check size
             self.assertEqual(A_						,(1, 3, 3_84, 3_84)				)

             with torch.no_grad():
                   __SCREAMING_SNAKE_CASE  :Union[str, Any]													=    model(**A_				)
             # masks_queries_logits
             __SCREAMING_SNAKE_CASE  :List[Any]													=    outputs.masks_queries_logits
             self.assertEqual(
                 masks_queries_logits.shape						,(1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)				)
             __SCREAMING_SNAKE_CASE  :Tuple													=    [
                 [-8.7_8_3_9, -9.0_0_5_6, -8.8_1_2_1],
                 [-7.4_1_0_4, -7.0_3_1_3, -6.5_4_0_1],
                 [-6.6_1_0_5, -6.3_4_2_7, -6.4_6_7_5],
             ]
             __SCREAMING_SNAKE_CASE  :int													=    torch.tensor(A_				).to(A_				)
             self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]						,A_						,atol=A_				)				)
             # class_queries_logits
             __SCREAMING_SNAKE_CASE  :List[Any]													=    outputs.class_queries_logits
             self.assertEqual(class_queries_logits.shape						,(1, model.config.num_queries, model.config.num_labels + 1)				)
             __SCREAMING_SNAKE_CASE  :int													=    torch.tensor(
                 [
                     [1.8_3_2_4, -8.0_8_3_5, -4.1_9_2_2],
                     [0.8_4_5_0, -9.0_0_5_0, -3.6_0_5_3],
                     [0.3_0_4_5, -7.7_2_9_3, -3.0_2_7_5],
                 ]				).to(A_				)
             self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]						,A_						,atol=A_				)				)




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





             """simple docstring"""






             __SCREAMING_SNAKE_CASE  :Optional[int]													=    MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints				).to(A_				).eval()
             __SCREAMING_SNAKE_CASE  :int													=    self.default_image_processor

             __SCREAMING_SNAKE_CASE  :int													=    image_processor(
                 [np.zeros((3, 8_00, 13_33)				), np.zeros((3, 8_00, 13_33)				)]						,segmentation_maps=[np.zeros((3_84, 3_84)				).astype(np.floataa				), np.zeros((3_84, 3_84)				).astype(np.floataa				)]						,return_tensors='''pt'''						,)

             __SCREAMING_SNAKE_CASE  :Optional[Any]													=    inputs['''pixel_values'''].to(A_				)
             __SCREAMING_SNAKE_CASE  :Union[str, Any]													=    [el.to(A_				) for el in inputs['''mask_labels''']]
             __SCREAMING_SNAKE_CASE  :Optional[int]													=    [el.to(A_				) for el in inputs['''class_labels''']]

             with torch.no_grad():
                   __SCREAMING_SNAKE_CASE  :int													=    model(**A_				)

             self.assertTrue(outputs.loss is not None				)



"""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 BatchEncoding, PreTrainedTokenizer
from ...utils import logging


UpperCAmelCase__					=logging.get_logger(__name__)

UpperCAmelCase__					="▁"

UpperCAmelCase__					={
    "vocab_file": "vocab.json",
    "spm_file": "sentencepiece.bpe.model",
    "tokenizer_config_file": "tokenizer_config.json",
}

UpperCAmelCase__					={
    "vocab_file": {
        "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json",
        "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json",
    },
    "spm_file": {
        "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model",
        "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model",
    },
    "tokenizer_config_file": {
        "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json",
        "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json",
    },
}

UpperCAmelCase__					={
    "facebook/m2m100_418M": 1024,
}

# fmt: off
UpperCAmelCase__					={
    "m2m100": ["af", "am", "ar", "ast", "az", "ba", "be", "bg", "bn", "br", "bs", "ca", "ceb", "cs", "cy", "da", "de", "el", "en", "es", "et", "fa", "ff", "fi", "fr", "fy", "ga", "gd", "gl", "gu", "ha", "he", "hi", "hr", "ht", "hu", "hy", "id", "ig", "ilo", "is", "it", "ja", "jv", "ka", "kk", "km", "kn", "ko", "lb", "lg", "ln", "lo", "lt", "lv", "mg", "mk", "ml", "mn", "mr", "ms", "my", "ne", "nl", "no", "ns", "oc", "or", "pa", "pl", "ps", "pt", "ro", "ru", "sd", "si", "sk", "sl", "so", "sq", "sr", "ss", "su", "sv", "sw", "ta", "th", "tl", "tn", "tr", "uk", "ur", "uz", "vi", "wo", "xh", "yi", "yo", "zh", "zu"],
    "wmt21": ["en", "ha", "is", "ja", "cs", "ru", "zh", "de"]
}





class  lowerCamelCase__    (		_a     ):
      a			:  str           =		VOCAB_FILES_NAMES
      a			:  Dict           =		PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      a			:  int           =		PRETRAINED_VOCAB_FILES_MAP
      a			:  Union[str, Any]           =		["""input_ids""", """attention_mask"""]

      a			:  List[int]           =		[]
      a			:  List[int]           =		[]
      def __init__(		self						:						Optional[Any]   ,							A_						:						str   ,							A_						:						Dict   ,							A_						:						str=None   ,							A_						:						Dict=None   ,							A_						:						str="<s>"   ,							A_						:						Any="</s>"   ,							A_						:						List[Any]="</s>"   ,							A_						:						List[str]="<pad>"   ,							A_						:						Optional[int]="<unk>"   ,							A_						:						str="m2m100"   ,							A_						:						Optional[Dict[str, Any]] = None   ,							A_						:						Tuple=8   ,							**A_						:						Dict   ,							):






       '''simple docstring'''


       __lowercase						=						{} if sp_model_kwargs is None else sp_model_kwargs

       __lowercase						=						language_codes
       __lowercase						=						FAIRSEQ_LANGUAGE_CODES[language_codes]
       __lowercase						=						{lang_code: F'''__{lang_code}__''' for lang_code in fairseq_language_code}

       __lowercase						=						kwargs.get("""additional_special_tokens"""   ,							[]				)
       kwargs["additional_special_tokens"] += [
           self.get_lang_token(A_				)
           for lang_code in fairseq_language_code
           if self.get_lang_token(A_				) not in kwargs["additional_special_tokens"]
       ]

       super().__init__(
           src_lang=A_   ,							tgt_lang=A_   ,							bos_token=A_   ,							eos_token=A_   ,							sep_token=A_   ,							unk_token=A_   ,							pad_token=A_   ,							language_codes=A_   ,							sp_model_kwargs=self.sp_model_kwargs   ,							num_madeup_words=A_   ,							**A_   ,							)

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

       __lowercase						=						len(self.encoder				)

       __lowercase						=						{
           self.get_lang_token(A_				): self.encoder_size + i for i, lang_code in enumerate(A_				)
       }
       __lowercase						=						{lang_code: self.encoder_size + i for i, lang_code in enumerate(A_				)}
       __lowercase						=						{v: k for k, v in self.lang_token_to_id.items()}

       __lowercase						=						src_lang if src_lang is not None else """en"""
       __lowercase						=						tgt_lang
       __lowercase						=						self.get_lang_id(self._src_lang				)
       self.set_src_lang_special_tokens(self._src_lang				)

       __lowercase						=						num_madeup_words
      @property
      def SCREAMING_SNAKE_CASE_						(		self						:						Union[str, Any]				):






       '''simple docstring'''


       return len(self.encoder				) + len(self.lang_token_to_id				)
      @property
      def SCREAMING_SNAKE_CASE_						(		self						:						Dict				):






       '''simple docstring'''


       return self._src_lang
      @src_lang.setter
      def SCREAMING_SNAKE_CASE_						(		self						:						Dict   ,							A_						:						str				):






       '''simple docstring'''


       __lowercase						=						new_src_lang
       self.set_src_lang_special_tokens(self._src_lang				)
      def SCREAMING_SNAKE_CASE_						(		self						:						Dict   ,							A_						:						str				):






       '''simple docstring'''


       return self.sp_model.encode(A_   ,							out_type=A_				)
      def SCREAMING_SNAKE_CASE_						(		self						:						Optional[Any]   ,							A_						:						str				):






       '''simple docstring'''


       if token in self.lang_token_to_id:
        return self.lang_token_to_id[token]
       return self.encoder.get(A_   ,							self.encoder[self.unk_token]				)
      def SCREAMING_SNAKE_CASE_						(		self						:						List[str]   ,							A_						:						int				):






       '''simple docstring'''


       if index in self.id_to_lang_token:
        return self.id_to_lang_token[index]
       return self.decoder.get(A_   ,							self.unk_token				)
      def SCREAMING_SNAKE_CASE_						(		self						:						Tuple   ,							A_						:						Union[str, Any]				):






       '''simple docstring'''


       __lowercase						=						[]
       __lowercase						=						""""""
       for token in tokens:
        # make sure that special tokens are not decoded using sentencepiece model
        if token in self.all_special_tokens:
         out_string += self.sp_model.decode(A_				) + token
         __lowercase						=						[]
        else:
         current_sub_tokens.append(A_				)
       out_string += self.sp_model.decode(A_				)
       return out_string.strip()
      def SCREAMING_SNAKE_CASE_						(		self						:						List[str]   ,							A_						:						List[int]   ,							A_						:						Optional[List[int]] = None   ,							A_						:						bool = False				):






       '''simple docstring'''


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

       __lowercase						=						[1] * len(self.prefix_tokens				)
       __lowercase						=						[1] * len(self.suffix_tokens				)
       if token_ids_a is None:
        return prefix_ones + ([0] * len(A_				)) + suffix_ones
       return prefix_ones + ([0] * len(A_				)) + ([0] * len(A_				)) + suffix_ones
      def SCREAMING_SNAKE_CASE_						(		self						:						Any   ,							A_						:						List[int]   ,							A_						:						Optional[List[int]] = None				):






       '''simple docstring'''


       if token_ids_a is None:
        return self.prefix_tokens + token_ids_a + self.suffix_tokens
       # 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.suffix_tokens
      def SCREAMING_SNAKE_CASE_						(		self						:						List[str]				):






       '''simple docstring'''


       __lowercase						=						{self.convert_ids_to_tokens(A_				): i for i in range(self.vocab_size				)}
       vocab.update(self.added_tokens_encoder				)
       return vocab
      def __getstate__(		self						:						List[str]				):






       '''simple docstring'''


       __lowercase						=						self.__dict__.copy()
       __lowercase						=						None
       return state
      def __setstate__(		self						:						Optional[Any]   ,							A_						:						Dict				):






       '''simple docstring'''


       __lowercase						=						d

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

       __lowercase						=						load_spm(self.spm_file   ,							self.sp_model_kwargs				)
      def SCREAMING_SNAKE_CASE_						(		self						:						Tuple   ,							A_						:						str   ,							A_						:						Optional[str] = None				):






       '''simple docstring'''


       __lowercase						=						Path(A_				)
       if not save_dir.is_dir():
        raise OSError(F'''{save_directory} should be a directory'''				)
       __lowercase						=						save_dir / (
           (filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""vocab_file"""]
       )
       __lowercase						=						save_dir / (
           (filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""spm_file"""]
       )

       save_json(self.encoder   ,							A_				)

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

       return (str(A_				), str(A_				))
      def SCREAMING_SNAKE_CASE_						(		self						:						List[Any]   ,							A_						:						List[str]   ,							A_						:						str = "en"   ,							A_						:						Optional[List[str]] = None   ,							A_						:						str = "ro"   ,							**A_						:						List[Any]   ,							):






       '''simple docstring'''


       __lowercase						=						src_lang
       __lowercase						=						tgt_lang
       self.set_src_lang_special_tokens(self.src_lang				)
       return super().prepare_seqaseq_batch(A_   ,							A_   ,							**A_				)
      def SCREAMING_SNAKE_CASE_						(		self						:						Optional[int]   ,							A_						:						List[Any]   ,							A_						:						Optional[str]   ,							A_						:						Optional[str]   ,							**A_						:						Optional[Any]				):






       '''simple docstring'''


       if src_lang is None or tgt_lang is None:
        raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model"""				)
       __lowercase						=						src_lang
       __lowercase						=						self(A_   ,							add_special_tokens=A_   ,							**A_				)
       __lowercase						=						self.get_lang_id(A_				)
       __lowercase						=						tgt_lang_id
       return inputs
      def SCREAMING_SNAKE_CASE_						(		self						:						List[str]				):






       '''simple docstring'''


       self.set_src_lang_special_tokens(self.src_lang				)
      def SCREAMING_SNAKE_CASE_						(		self						:						Optional[int]				):






       '''simple docstring'''


       self.set_tgt_lang_special_tokens(self.tgt_lang				)
      def SCREAMING_SNAKE_CASE_						(		self						:						Optional[Any]   ,							A_						:						str				):






       '''simple docstring'''


       __lowercase						=						self.get_lang_token(A_				)
       __lowercase						=						self.lang_token_to_id[lang_token]
       __lowercase						=						[self.cur_lang_id]
       __lowercase						=						[self.eos_token_id]
      def SCREAMING_SNAKE_CASE_						(		self						:						Optional[int]   ,							A_						:						str				):






       '''simple docstring'''


       __lowercase						=						self.get_lang_token(A_				)
       __lowercase						=						self.lang_token_to_id[lang_token]
       __lowercase						=						[self.cur_lang_id]
       __lowercase						=						[self.eos_token_id]
      def SCREAMING_SNAKE_CASE_						(		self						:						Dict   ,							A_						:						str				):






       '''simple docstring'''


       return self.lang_code_to_token[lang]






      def SCREAMING_SNAKE_CASE_						(		self						:						Dict   ,							A_						:						str				):






       '''simple docstring'''


       __lowercase						=						self.get_lang_token(A_				)
       return self.lang_token_to_id[lang_token]






def lowerCAmelCase_   (					UpperCamelCase__						:			str					, UpperCamelCase__						:			Dict[str, Any]			):






 """simple docstring"""







 __lowercase						=						sentencepiece.SentencePieceProcessor(**UpperCamelCase__			)
 spm.Load(str(UpperCamelCase__			)			)
 return spm


def lowerCAmelCase_   (					UpperCamelCase__						:			str			):






 """simple docstring"""







 with open(UpperCamelCase__					, """r"""			) as f:
  return json.load(UpperCamelCase__			)


def lowerCAmelCase_   (					UpperCamelCase__						:			List[str]					, UpperCamelCase__						:			str			):






 """simple docstring"""







 with open(UpperCamelCase__					, """w"""			) as f:
  json.dump(UpperCamelCase__					, UpperCamelCase__					, indent=2			)
