





import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

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


__A									=				logging.get_logger(__name__)

__A									=				"▁"

__A									=				{"vocab_file": "sentencepiece.bpe.model"}

__A									=				{
    "vocab_file": {
        "facebook/xglm-564M": "https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model",
    }
}

__A									=				{
    "facebook/xglm-564M": 2048,
}



class    _SCREAMING_SNAKE_CASE						(	__SCREAMING_SNAKE_CASE    ):







 '''simple docstring'''
 lowercase_		=			VOCAB_FILES_NAMES
 lowercase_		=			PRETRAINED_VOCAB_FILES_MAP
 lowercase_		=			PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 lowercase_		=			["input_ids", "attention_mask"]

 def __init__(self				:   List[Any]       , UpperCAmelCase_				:   List[Any]       , UpperCAmelCase_				:   Any="<s>"       , UpperCAmelCase_				:   Optional[int]="</s>"       , UpperCAmelCase_				:   List[Any]="</s>"       , UpperCAmelCase_				:   Union[str, Any]="<s>"       , UpperCAmelCase_				:   Any="<unk>"       , UpperCAmelCase_				:   str="<pad>"       , UpperCAmelCase_				:   Optional[Dict[str, Any]] = None       , **UpperCAmelCase_				:   str       , )       ->None:



   '''simple docstring'''



   lowerCamelCase__:      Dict			  ={} if sp_model_kwargs is None else sp_model_kwargs

   # Compatibility with the original tokenizer
   lowerCamelCase__:      Tuple			  =7
   lowerCamelCase__:      int			  =[F"""<madeupword{i}>""" for i in range(self.num_madeup_words)]

   lowerCamelCase__:      str			  =kwargs.get("additional_special_tokens"       , [])
   kwargs["additional_special_tokens"] += [
       word for word in madeup_words if word not in kwargs["additional_special_tokens"]
   ]

   super().__init__(
       bos_token=UpperCAmelCase_       , eos_token=UpperCAmelCase_       , unk_token=UpperCAmelCase_       , sep_token=UpperCAmelCase_       , cls_token=UpperCAmelCase_       , pad_token=UpperCAmelCase_       , sp_model_kwargs=self.sp_model_kwargs       , **UpperCAmelCase_       , )

   lowerCamelCase__:      Any			  =spm.SentencePieceProcessor(**self.sp_model_kwargs)
   self.sp_model.Load(str(UpperCAmelCase_))
   lowerCamelCase__:      List[str]			  =vocab_file

   # Original fairseq vocab and spm vocab must be "aligned":
   # Vocab    |    0    |    1    |   2    |    3    |  4  |  5  |  6  |   7   |   8   |  9
   # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
   # fairseq  | '<s>'   | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's'   | '▁de' | '-'
   # spm      | '<unk>' | '<s>'   | '</s>' | ','     | '.' | '▁' | 's' | '▁de' | '-'   | '▁a'

   # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
   lowerCamelCase__:      Union[str, Any]			  =1

   # Mimic fairseq token-to-id alignment for the first 4 token
   lowerCamelCase__:      Union[str, Any]			  ={"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3}

   lowerCamelCase__:      Any			  =len(self.sp_model)
   lowerCamelCase__:      Tuple			  ={F"""<madeupword{i}>""": sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words)}
   self.fairseq_tokens_to_ids.update(UpperCAmelCase_)

   lowerCamelCase__:      int			  ={v: k for k, v in self.fairseq_tokens_to_ids.items()}

 def __getstate__(self				:   Dict)       ->List[str]:



   '''simple docstring'''



   lowerCamelCase__:      List[Any]			  =self.__dict__.copy()
   lowerCamelCase__:      str			  =None
   lowerCamelCase__:      Any			  =self.sp_model.serialized_model_proto()
   return state

 def __setstate__(self				:   Any       , UpperCAmelCase_				:   Tuple)       ->Optional[int]:



   '''simple docstring'''



   lowerCamelCase__:      Optional[Any]			  =d

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

   lowerCamelCase__:      str			  =spm.SentencePieceProcessor(**self.sp_model_kwargs)
   self.sp_model.LoadFromSerializedProto(self.sp_model_proto)

 def 							SCREAMING_SNAKE_CASE_					(self				:   List[str]       , UpperCAmelCase_				:   List[int]       , UpperCAmelCase_				:   Optional[List[int]] = None)       ->List[int]:



   '''simple docstring'''



   if token_ids_a is None:
     return [self.sep_token_id] + token_ids_a
   lowerCamelCase__:      Any			  =[self.sep_token_id]
   return sep + token_ids_a + sep + sep + token_ids_a

 def 							SCREAMING_SNAKE_CASE_					(self				:   int       , UpperCAmelCase_				:   List[int]       , UpperCAmelCase_				:   Optional[List[int]] = None       , UpperCAmelCase_				:   bool = False)       ->List[int]:



   '''simple docstring'''



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

   if token_ids_a is None:
     return [1] + ([0] * len(UpperCAmelCase_))
   return [1] + ([0] * len(UpperCAmelCase_)) + [1, 1] + ([0] * len(UpperCAmelCase_))

 def 							SCREAMING_SNAKE_CASE_					(self				:   Dict       , UpperCAmelCase_				:   List[int]       , UpperCAmelCase_				:   Optional[List[int]] = None)       ->List[int]:



   '''simple docstring'''



   lowerCamelCase__:      List[str]			  =[self.sep_token_id]

   if token_ids_a is None:
     return len(sep + token_ids_a) * [0]
   return len(sep + token_ids_a + sep + sep + token_ids_a) * [0]

 @property
 def 							SCREAMING_SNAKE_CASE_					(self				:   List[Any])       ->Optional[int]:



   '''simple docstring'''



   return len(self.sp_model) + self.fairseq_offset + self.num_madeup_words

 def 							SCREAMING_SNAKE_CASE_					(self				:   int)       ->str:



   '''simple docstring'''



   lowerCamelCase__:      str			  ={self.convert_ids_to_tokens(UpperCAmelCase_): i for i in range(self.vocab_size)}
   vocab.update(self.added_tokens_encoder)
   return vocab

 def 							SCREAMING_SNAKE_CASE_					(self				:   Any       , UpperCAmelCase_				:   str)       ->List[str]:



   '''simple docstring'''



   return self.sp_model.encode(UpperCAmelCase_       , out_type=UpperCAmelCase_)

 def 							SCREAMING_SNAKE_CASE_					(self				:   List[str]       , UpperCAmelCase_				:   Union[str, Any])       ->Dict:



   '''simple docstring'''



   if token in self.fairseq_tokens_to_ids:
     return self.fairseq_tokens_to_ids[token]
   lowerCamelCase__:      Optional[int]			  =self.sp_model.PieceToId(UpperCAmelCase_)

   # Need to return unknown token if the SP model returned 0
   return spm_id + self.fairseq_offset if spm_id else self.unk_token_id

 def 							SCREAMING_SNAKE_CASE_					(self				:   List[str]       , UpperCAmelCase_				:   List[str])       ->Optional[Any]:



   '''simple docstring'''



   if index in self.fairseq_ids_to_tokens:
     return self.fairseq_ids_to_tokens[index]
   return self.sp_model.IdToPiece(index - self.fairseq_offset)

 def 							SCREAMING_SNAKE_CASE_					(self				:   Any       , UpperCAmelCase_				:   Dict)       ->Dict:



   '''simple docstring'''



   lowerCamelCase__:      str			  ="".join(UpperCAmelCase_).replace(UpperCAmelCase_       , " ").strip()
   return out_string







 def 							SCREAMING_SNAKE_CASE_					(self				:   Dict       , UpperCAmelCase_				:   str       , UpperCAmelCase_				:   Optional[str] = None)       ->Tuple[str]:



   '''simple docstring'''



   if not os.path.isdir(UpperCAmelCase_):
     logger.error(F"""Vocabulary path ({save_directory}) should be a directory""")
     return
   lowerCamelCase__:      List[str]			  =os.path.join(
       UpperCAmelCase_       , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"])

   if os.path.abspath(self.vocab_file) != os.path.abspath(UpperCAmelCase_) and os.path.isfile(self.vocab_file):
     copyfile(self.vocab_file       , UpperCAmelCase_)
   elif not os.path.isfile(self.vocab_file):
     with open(UpperCAmelCase_       , "wb") as fi:
       lowerCamelCase__:      Optional[int]			  =self.sp_model.serialized_model_proto()
       fi.write(UpperCAmelCase_)

   return (out_vocab_file,)








import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
     import torch

if is_vision_available():
     from PIL import Image

     from transformers import PoolFormerImageProcessor



class    _SCREAMING_SNAKE_CASE						(	unittest.TestCase    ):







 '''simple docstring'''

 def __init__(self				:   List[Any]       , UpperCAmelCase_				:   Any       , UpperCAmelCase_				:   Dict=7       , UpperCAmelCase_				:   List[str]=3       , UpperCAmelCase_				:   str=30       , UpperCAmelCase_				:   List[str]=400       , UpperCAmelCase_				:   Optional[int]=True       , UpperCAmelCase_				:   Optional[int]=None       , UpperCAmelCase_				:   Tuple=0.9       , UpperCAmelCase_				:   str=None       , UpperCAmelCase_				:   int=True       , UpperCAmelCase_				:   Union[str, Any]=[0.5, 0.5, 0.5]       , UpperCAmelCase_				:   Optional[Any]=[0.5, 0.5, 0.5]       , )       ->str:



   '''simple docstring'''



   lowerCamelCase__:      List[Any]			  =size if size is not None else {"shortest_edge": 30}
   lowerCamelCase__:      Dict			  =crop_size if crop_size is not None else {"height": 30, "width": 30}
   lowerCamelCase__:      Any			  =parent
   lowerCamelCase__:      Any			  =batch_size
   lowerCamelCase__:      Optional[Any]			  =num_channels
   lowerCamelCase__:      Tuple			  =min_resolution
   lowerCamelCase__:      Union[str, Any]			  =max_resolution
   lowerCamelCase__:      Union[str, Any]			  =do_resize_and_center_crop
   lowerCamelCase__:      Optional[int]			  =size
   lowerCamelCase__:      str			  =crop_pct
   lowerCamelCase__:      Any			  =crop_size
   lowerCamelCase__:      List[str]			  =do_normalize
   lowerCamelCase__:      List[str]			  =image_mean
   lowerCamelCase__:      Tuple			  =image_std







 def 							SCREAMING_SNAKE_CASE_					(self				:   List[Any])       ->Optional[int]:



   '''simple docstring'''



   return {
       "size": self.size,
       "do_resize_and_center_crop": self.do_resize_and_center_crop,
       "crop_pct": self.crop_pct,
       "crop_size": self.crop_size,
       "do_normalize": self.do_normalize,
       "image_mean": self.image_mean,
       "image_std": self.image_std,
   }



@require_torch
@require_vision
class    _SCREAMING_SNAKE_CASE						(	__SCREAMING_SNAKE_CASE    ,							unittest.TestCase    ):







 '''simple docstring'''
 lowercase_		=			PoolFormerImageProcessor if is_vision_available() else None

 def 							SCREAMING_SNAKE_CASE_					(self				:   Optional[int])       ->Optional[Any]:



   '''simple docstring'''



   lowerCamelCase__:      Optional[int]			  =PoolFormerImageProcessingTester(self)

 @property
 def 							SCREAMING_SNAKE_CASE_					(self				:   str)       ->int:



   '''simple docstring'''



   return self.image_processor_tester.prepare_image_processor_dict()

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



   '''simple docstring'''



   lowerCamelCase__:      Any			  =self.image_processing_class(**self.image_processor_dict)
   self.assertTrue(hasattr(UpperCAmelCase_       , "do_resize_and_center_crop"))
   self.assertTrue(hasattr(UpperCAmelCase_       , "size"))
   self.assertTrue(hasattr(UpperCAmelCase_       , "crop_pct"))
   self.assertTrue(hasattr(UpperCAmelCase_       , "do_normalize"))
   self.assertTrue(hasattr(UpperCAmelCase_       , "image_mean"))
   self.assertTrue(hasattr(UpperCAmelCase_       , "image_std"))

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



   '''simple docstring'''



   lowerCamelCase__:      List[str]			  =self.image_processing_class.from_dict(self.image_processor_dict)
   self.assertEqual(image_processor.size       , {"shortest_edge": 30})
   self.assertEqual(image_processor.crop_size       , {"height": 30, "width": 30})

   lowerCamelCase__:      Union[str, Any]			  =self.image_processing_class.from_dict(self.image_processor_dict       , size=42       , crop_size=84)
   self.assertEqual(image_processor.size       , {"shortest_edge": 42})
   self.assertEqual(image_processor.crop_size       , {"height": 84, "width": 84})

 def 							SCREAMING_SNAKE_CASE_					(self				:   int)       ->Optional[Any]:



   '''simple docstring'''



   pass

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



   '''simple docstring'''



   lowerCamelCase__:      Union[str, Any]			  =self.image_processing_class(**self.image_processor_dict)
   # create random PIL images
   lowerCamelCase__:      Union[str, Any]			  =prepare_image_inputs(self.image_processor_tester       , equal_resolution=UpperCAmelCase_)
   for image in image_inputs:
     self.assertIsInstance(UpperCAmelCase_       , Image.Image)

   # Test not batched input
   lowerCamelCase__:      Dict			  =image_processing(image_inputs[0]       , return_tensors="pt").pixel_values

   self.assertEqual(
       encoded_images.shape       , (
           1,
           self.image_processor_tester.num_channels,
           self.image_processor_tester.crop_size["height"],
           self.image_processor_tester.crop_size["width"],
       )       , )

   # Test batched
   lowerCamelCase__:      int			  =image_processing(UpperCAmelCase_       , return_tensors="pt").pixel_values
   self.assertEqual(
       encoded_images.shape       , (
           self.image_processor_tester.batch_size,
           self.image_processor_tester.num_channels,
           self.image_processor_tester.crop_size["height"],
           self.image_processor_tester.crop_size["width"],
       )       , )

 def 							SCREAMING_SNAKE_CASE_					(self				:   Optional[Any])       ->Dict:



   '''simple docstring'''



   lowerCamelCase__:      Any			  =self.image_processing_class(**self.image_processor_dict)
   # create random numpy tensors
   lowerCamelCase__:      Tuple			  =prepare_image_inputs(self.image_processor_tester       , equal_resolution=UpperCAmelCase_       , numpify=UpperCAmelCase_)
   for image in image_inputs:
     self.assertIsInstance(UpperCAmelCase_       , np.ndarray)

   # Test not batched input
   lowerCamelCase__:      Union[str, Any]			  =image_processing(image_inputs[0]       , return_tensors="pt").pixel_values
   self.assertEqual(
       encoded_images.shape       , (
           1,
           self.image_processor_tester.num_channels,
           self.image_processor_tester.crop_size["height"],
           self.image_processor_tester.crop_size["width"],
       )       , )

   # Test batched
   lowerCamelCase__:      List[str]			  =image_processing(UpperCAmelCase_       , return_tensors="pt").pixel_values
   self.assertEqual(
       encoded_images.shape       , (
           self.image_processor_tester.batch_size,
           self.image_processor_tester.num_channels,
           self.image_processor_tester.crop_size["height"],
           self.image_processor_tester.crop_size["width"],
       )       , )







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



   '''simple docstring'''



   lowerCamelCase__:      Optional[int]			  =self.image_processing_class(**self.image_processor_dict)
   # create random PyTorch tensors
   lowerCamelCase__:      Any			  =prepare_image_inputs(self.image_processor_tester       , equal_resolution=UpperCAmelCase_       , torchify=UpperCAmelCase_)
   for image in image_inputs:
     self.assertIsInstance(UpperCAmelCase_       , torch.Tensor)

   # Test not batched input
   lowerCamelCase__:      Any			  =image_processing(image_inputs[0]       , return_tensors="pt").pixel_values
   self.assertEqual(
       encoded_images.shape       , (
           1,
           self.image_processor_tester.num_channels,
           self.image_processor_tester.crop_size["height"],
           self.image_processor_tester.crop_size["width"],
       )       , )

   # Test batched
   lowerCamelCase__:      str			  =image_processing(UpperCAmelCase_       , return_tensors="pt").pixel_values
   self.assertEqual(
       encoded_images.shape       , (
           self.image_processor_tester.batch_size,
           self.image_processor_tester.num_channels,
           self.image_processor_tester.crop_size["height"],
           self.image_processor_tester.crop_size["width"],
       )       , )

