




'''simple docstring'''


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


if is_torch_available():
 import torch

if is_vision_available():
 from PIL import Image

 from transformers import ChineseCLIPImageProcessor







class      SCREAMING_SNAKE_CASE    (						unittest.TestCase				):






      def __init__( self   :  List[str]						,						lowercase__   :  List[str]						,						lowercase__   :  List[Any]=7						,						lowercase__   :  Union[str, Any]=3						,						lowercase__   :  int=18						,						lowercase__   :  Any=30						,						lowercase__   :  Union[str, Any]=400						,						lowercase__   :  List[Any]=True						,						lowercase__   :  Dict=None						,						lowercase__   :  Any=True						,						lowercase__   :  Optional[Any]=None						,						lowercase__   :  Union[str, Any]=True						,						lowercase__   :  Dict=[0.48145466, 0.4578275, 0.40821073]						,						lowercase__   :  List[Any]=[0.26862954, 0.26130258, 0.27577711]						,						lowercase__   :  Optional[int]=True						,						):


           '''simple docstring'''

           a_     :							List[str]     						=  size if size is not None else {"""height""": 224, """width""": 224}
           a_     :							str     						=  crop_size if crop_size is not None else {"""height""": 18, """width""": 18}
           a_     :							List[Any]     						=  parent
           a_     :							List[str]     						=  batch_size
           a_     :							Optional[Any]     						=  num_channels
           a_     :							Any     						=  image_size
           a_     :							Tuple     						=  min_resolution
           a_     :							Dict     						=  max_resolution
           a_     :							Optional[Any]     						=  do_resize
           a_     :							Optional[Any]     						=  size
           a_     :							Dict     						=  do_center_crop
           a_     :							Any     						=  crop_size
           a_     :							List[str]     						=  do_normalize
           a_     :							Tuple     						=  image_mean
           a_     :							Tuple     						=  image_std
           a_     :							Any     						=  do_convert_rgb






      def 							lowercase_						( self   :  List[str]       ):


           '''simple docstring'''

           return {
               "do_resize": self.do_resize,
               "size": self.size,
               "do_center_crop": self.do_center_crop,
               "crop_size": self.crop_size,
               "do_normalize": self.do_normalize,
               "image_mean": self.image_mean,
               "image_std": self.image_std,
               "do_convert_rgb": self.do_convert_rgb,
           }






      def 							lowercase_						( self   :  str						,						lowercase__   :  List[Any]=False						,						lowercase__   :  int=False						,						lowercase__   :  List[str]=False       ):


           '''simple docstring'''

           assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

           if equal_resolution:
                a_     :							str     						=  []
                for i in range(self.batch_size       ):
                     image_inputs.append(
                         np.random.randint(
                             255						,						size=(self.num_channels, self.max_resolution, self.max_resolution)						,						dtype=np.uinta       )       )
           else:
                a_     :							Optional[Any]     						=  []
                for i in range(self.batch_size       ):
                     a_						,     a_     :							Dict     						=  np.random.choice(np.arange(self.min_resolution						,						self.max_resolution       )						,						2       )
                     image_inputs.append(np.random.randint(255						,						size=(self.num_channels, width, height)						,						dtype=np.uinta       )       )

           if not numpify and not torchify:
                # PIL expects the channel dimension as last dimension
                a_     :							Tuple     						=  [Image.fromarray(np.moveaxis(lowercase__						,						0						,						-1       )       ) for x in image_inputs]

           if torchify:
                a_     :							Any     						=  [torch.from_numpy(lowercase__       ) for x in image_inputs]

           return image_inputs







@require_torch
@require_vision
class      SCREAMING_SNAKE_CASE    (						snake_case_							,      unittest.TestCase				):
      __magic_name__  :       Optional[int]   							=					ChineseCLIPImageProcessor if is_vision_available() else None






      def 							lowercase_						( self   :  List[str]       ):


           '''simple docstring'''

           a_     :							int     						=  ChineseCLIPImageProcessingTester(self						,						do_center_crop=lowercase__       )






      @property
      def 							lowercase_						( self   :  Any       ):


           '''simple docstring'''

           return self.image_processor_tester.prepare_image_processor_dict()






      def 							lowercase_						( self   :  Any       ):


           '''simple docstring'''

           a_     :							int     						=  self.image_processing_class(**self.image_processor_dict       )
           self.assertTrue(hasattr(lowercase__						,						"""do_resize"""       )       )
           self.assertTrue(hasattr(lowercase__						,						"""size"""       )       )
           self.assertTrue(hasattr(lowercase__						,						"""do_center_crop"""       )       )
           self.assertTrue(hasattr(lowercase__						,						"""center_crop"""       )       )
           self.assertTrue(hasattr(lowercase__						,						"""do_normalize"""       )       )
           self.assertTrue(hasattr(lowercase__						,						"""image_mean"""       )       )
           self.assertTrue(hasattr(lowercase__						,						"""image_std"""       )       )
           self.assertTrue(hasattr(lowercase__						,						"""do_convert_rgb"""       )       )






      def 							lowercase_						( self   :  Tuple       ):


           '''simple docstring'''

           a_     :							str     						=  self.image_processing_class.from_dict(self.image_processor_dict       )
           self.assertEqual(image_processor.size						,						{"""height""": 224, """width""": 224}       )
           self.assertEqual(image_processor.crop_size						,						{"""height""": 18, """width""": 18}       )

           a_     :							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 							lowercase_						( self   :  Union[str, Any]       ):


           '''simple docstring'''

           pass






      def 							lowercase_						( self   :  Any       ):


           '''simple docstring'''

           a_     :							Optional[int]     						=  self.image_processing_class(**self.image_processor_dict       )
           # create random PIL images
           a_     :							str     						=  self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__       )
           for image in image_inputs:
                self.assertIsInstance(lowercase__						,						Image.Image       )

           # Test not batched input
           a_     :							Tuple     						=  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
           a_     :							Optional[Any]     						=  image_processing(lowercase__						,						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 							lowercase_						( self   :  Dict       ):


           '''simple docstring'''

           a_     :							List[str]     						=  self.image_processing_class(**self.image_processor_dict       )
           # create random numpy tensors
           a_     :							Optional[Any]     						=  self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__						,						numpify=lowercase__       )
           for image in image_inputs:
                self.assertIsInstance(lowercase__						,						np.ndarray       )

           # Test not batched input
           a_     :							Tuple     						=  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
           a_     :							Any     						=  image_processing(lowercase__						,						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 							lowercase_						( self   :  List[Any]       ):


           '''simple docstring'''

           a_     :							List[Any]     						=  self.image_processing_class(**self.image_processor_dict       )
           # create random PyTorch tensors
           a_     :							int     						=  self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__						,						torchify=lowercase__       )
           for image in image_inputs:
                self.assertIsInstance(lowercase__						,						torch.Tensor       )

           # Test not batched input
           a_     :							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
           a_     :							Tuple     						=  image_processing(lowercase__						,						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"""],
               )						,						)







@require_torch
@require_vision
class      SCREAMING_SNAKE_CASE    (						snake_case_							,      unittest.TestCase				):
      __magic_name__  :       List[Any]   							=					ChineseCLIPImageProcessor if is_vision_available() else None






      def 							lowercase_						( self   :  List[str]       ):


           '''simple docstring'''

           a_     :							int     						=  ChineseCLIPImageProcessingTester(self						,						num_channels=4						,						do_center_crop=lowercase__       )
           a_     :							List[str]     						=  3






      @property
      def 							lowercase_						( self   :  Union[str, Any]       ):


           '''simple docstring'''

           return self.image_processor_tester.prepare_image_processor_dict()






      def 							lowercase_						( self   :  Tuple       ):


           '''simple docstring'''

           a_     :							List[str]     						=  self.image_processing_class(**self.image_processor_dict       )
           self.assertTrue(hasattr(lowercase__						,						"""do_resize"""       )       )
           self.assertTrue(hasattr(lowercase__						,						"""size"""       )       )
           self.assertTrue(hasattr(lowercase__						,						"""do_center_crop"""       )       )
           self.assertTrue(hasattr(lowercase__						,						"""center_crop"""       )       )
           self.assertTrue(hasattr(lowercase__						,						"""do_normalize"""       )       )
           self.assertTrue(hasattr(lowercase__						,						"""image_mean"""       )       )
           self.assertTrue(hasattr(lowercase__						,						"""image_std"""       )       )
           self.assertTrue(hasattr(lowercase__						,						"""do_convert_rgb"""       )       )






      def 							lowercase_						( self   :  Optional[int]       ):


           '''simple docstring'''

           pass






      def 							lowercase_						( self   :  int       ):


           '''simple docstring'''

           a_     :							Tuple     						=  self.image_processing_class(**self.image_processor_dict       )
           # create random PIL images
           a_     :							List[str]     						=  self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__       )
           for image in image_inputs:
                self.assertIsInstance(lowercase__						,						Image.Image       )

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

           # Test batched
           a_     :							Dict     						=  image_processing(lowercase__						,						return_tensors="""pt"""       ).pixel_values
           self.assertEqual(
               encoded_images.shape						,						(
                   self.image_processor_tester.batch_size,
                   self.expected_encoded_image_num_channels,
                   self.image_processor_tester.crop_size["""height"""],
                   self.image_processor_tester.crop_size["""width"""],
               )						,						)






'''simple docstring'''


import os
import re
import unicodedata
from shutil import copyfile
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import is_torch_available, logging


if is_torch_available():
 import torch


if TYPE_CHECKING:
 from transformers.pipelines.conversational import Conversation


lowerCAmelCase_      :  List[str]				     =  logging.get_logger(__name__)
lowerCAmelCase_      :  List[str]				     =  {'vocab_file': 'spiece.model'}

lowerCAmelCase_      :  Union[str, Any]				     =  {
    'vocab_file': {
        'AI-Sweden/gpt-sw3-126m': 'https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model',
        'AI-Sweden/gpt-sw3-350m': 'https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model',
        'AI-Sweden/gpt-sw3-1.6b': 'https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model',
        'AI-Sweden/gpt-sw3-6.7b': 'https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model',
        'AI-Sweden/gpt-sw3-20b': 'https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model',
    }
}

lowerCAmelCase_      :  str				     =  {
    'AI-Sweden/gpt-sw3-126m': 2048,
    'AI-Sweden/gpt-sw3-350m': 2048,
    'AI-Sweden/gpt-sw3-1.6b': 2048,
    'AI-Sweden/gpt-sw3-6.7b': 2048,
    'AI-Sweden/gpt-sw3-20b': 2048,
}







class      SCREAMING_SNAKE_CASE    (						snake_case_				):
      __magic_name__  :       List[Any]   							=					VOCAB_FILES_NAMES
      __magic_name__  :       Dict   							=					PRETRAINED_VOCAB_FILES_MAP
      __magic_name__  :       Optional[int]   							=					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      __magic_name__  :       List[str]   							=					['''input_ids''', '''attention_mask''']






      def __init__( self   :  Union[str, Any]						,						lowercase__   :  Optional[Any]						,						lowercase__   :  Optional[Any]=False						,						lowercase__   :  Any=False						,						lowercase__   :  Optional[Any]=False						,						lowercase__   :  Dict=None						,						lowercase__   :  Any=None						,						lowercase__   :  List[str]=None						,						lowercase__   :  int=None						,						lowercase__   :  Optional[Dict[str, Any]] = None						,						**lowercase__   :  List[str]						,						):


           '''simple docstring'''

           a_     :							Any     						=  {} if sp_model_kwargs is None else sp_model_kwargs

           a_     :							Optional[Any]     						=  kwargs.get("""name_or_path"""       )
           if name_or_path is None:
                logger.warning(
                    """name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,"""
                    """ you are testing the model, this can safely be ignored"""       )
                a_     :							List[Any]     						=  """None"""

           # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing
           a_     :							Union[str, Any]     						=  """<|endoftext|>""" if eos_token is None else eos_token
           a_     :							Dict     						=  """<unk>""" if unk_token is None else unk_token
           if "gpt-sw3-7b" in name_or_path:
                a_     :							Tuple     						=  unk_token if pad_token is None else pad_token
                a_     :							Any     						=  eos_token if bos_token is None else bos_token
           else:
                a_     :							Optional[int]     						=  """<pad>""" if pad_token is None else pad_token
                a_     :							str     						=  """<s>""" if bos_token is None else bos_token

           super().__init__(
               do_lower_case=lowercase__						,						remove_space=lowercase__						,						keep_accents=lowercase__						,						bos_token=lowercase__						,						eos_token=lowercase__						,						unk_token=lowercase__						,						pad_token=lowercase__						,						sp_model_kwargs=self.sp_model_kwargs						,						**lowercase__						,						)

           a_     :							Optional[int]     						=  do_lower_case
           a_     :							Any     						=  remove_space
           a_     :							List[str]     						=  keep_accents
           a_     :							int     						=  vocab_file

           a_     :							Any     						=  spm.SentencePieceProcessor(**self.sp_model_kwargs       )
           self.sp_model.Load(lowercase__       )

           # Used for whitespace normalization in input texts
           # fmt : off
           a_     :							Dict     						=  {""" """, """ """, """ """, """ """, """ """, """　""", """ """, """ """, """ """, """ """, """￼""", """"""}
           # fmt : on

           # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing
           a_     :							Tuple     						=  re.compile(
               F"[{''.join(map(lowercase__						,						list(range(0						,						9       )       ) + list(range(11						,						32       )       ) + list(range(127						,						160       )       ) + [160, 173, 8203]       )       )}]"       )






      def __getstate__( self   :  str       ):


           '''simple docstring'''

           a_     :							Optional[int]     						=  self.__dict__.copy()
           a_     :							Tuple     						=  None
           return state






      def __setstate__( self   :  Tuple						,						lowercase__   :  Optional[int]       ):


           '''simple docstring'''

           a_     :							List[str]     						=  d

           # for backward compatibility
           if not hasattr(self						,						"""sp_model_kwargs"""       ):
                a_     :							Union[str, Any]     						=  {}

           a_     :							int     						=  spm.SentencePieceProcessor(**self.sp_model_kwargs       )
           self.sp_model.Load(self.vocab_file       )






      @property
      # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size
      def 							lowercase_						( self   :  Union[str, Any]       ):


           '''simple docstring'''

           return len(self.sp_model       )






      def 							lowercase_						( self   :  Union[str, Any]						,						lowercase__   :  str       ):


           '''simple docstring'''

           a_     :							Optional[int]     						=  self.non_printing_characters_re.sub(""""""						,						lowercase__       )

           # Normalize whitespaces
           a_     :							List[Any]     						=  """""".join([char if char not in self.whitespaces else """ """ for char in text]       )

           # NFC Unicode normalization
           a_     :							str     						=  unicodedata.normalize("""NFC"""						,						lowercase__       )
           return text






      def 							lowercase_						( self   :  Tuple						,						lowercase__   :  str						,						**lowercase__   :  Dict       ):


           '''simple docstring'''

           a_     :							Dict     						=  self.preprocess_text(lowercase__       )
           return self.sp_model.encode(lowercase__						,						out_type=lowercase__       )






      def 							lowercase_						( self   :  Optional[int]						,						lowercase__   :  str       ):


           '''simple docstring'''

           return self.sp_model.PieceToId(lowercase__       )






      def 							lowercase_						( self   :  Dict						,						lowercase__   :  int       ):


           '''simple docstring'''

           return self.sp_model.IdToPiece(lowercase__       )






      @staticmethod
      def 							lowercase_						( lowercase__   :  str       ):


           '''simple docstring'''

           return out_string






      def 							lowercase_						( self   :  Union[str, Any]						,						lowercase__   :  List[str]       ):


           '''simple docstring'''

           a_     :							Dict     						=  []
           a_     :							int     						=  """"""
           a_     :							Union[str, Any]     						=  False
           for token in tokens:
                # make sure that special tokens are not decoded using sentencepiece model
                if token in self.all_special_tokens:
                     # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document
                     if not prev_is_special:
                          out_string += " "

                     out_string += self.sp_model.decode(lowercase__       ) + token
                     a_     :							int     						=  True
                     a_     :							Optional[int]     						=  []
                else:
                     current_sub_tokens.append(lowercase__       )
                     a_     :							List[str]     						=  False
           out_string += self.sp_model.decode(lowercase__       )

           return out_string






      def 							lowercase_						( self   :  Dict       ):


           '''simple docstring'''

           a_     :							List[Any]     						=  {self.convert_ids_to_tokens(lowercase__       ): i for i in range(self.vocab_size       )}
           vocab.update(self.added_tokens_encoder       )
           return vocab






      def 							lowercase_						( self   :  Optional[Any]						,						lowercase__   :  str						,						lowercase__   :  Optional[str] = None       ):


           '''simple docstring'''

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

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

           return (out_vocab_file,)






      def 							lowercase_						( self   :  Union[str, Any]						,						lowercase__   :  Union[str, List[str]]						,						lowercase__   :  Union[str, bool] = False       ):


           '''simple docstring'''

           if isinstance(lowercase__						,						lowercase__       ):
                a_     :							List[str]     						=  self.preprocess_text(lowercase__       )
                a_     :							str     						=  self.sp_model.encode(lowercase__       )
           else:
                a_     :							Optional[Any]     						=  [self.preprocess_text(lowercase__       ) for t in text]
                a_     :							Any     						=  self.sp_model.encode(lowercase__       )

           if return_tensors is True or return_tensors == "pt":
                a_     :							Tuple     						=  torch.tensor(lowercase__       )

           return token_ids






      def 							lowercase_						( self   :  List[Any]						,						lowercase__   :  Union[int, List[int]]       ):


           '''simple docstring'''

           return self.sp_model.decode(lowercase__       )






      def 							lowercase_						( self   :  Dict						,						lowercase__   :  "Conversation"       ):


           '''simple docstring'''

           a_     :							Dict     						=  [F"User: {text}" if is_user else F"Bot: {text}" for is_user, text in conversation.iter_texts()]
           a_     :							Any     						=  (
               F"{self.eos_token}{self.bos_token}" + F"{self.bos_token}".join(lowercase__       ) + F"{self.bos_token}Bot:"
           )
           return self.encode(text=lowercase__       )
