





"""simple docstring"""





import importlib
import json
import os
from collections import OrderedDict
from typing import Dict, Optional, Union

# Build the list of all image processors
from ...configuration_utils import PretrainedConfig
from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
from ...image_processing_utils import ImageProcessingMixin
from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging
from .auto_factory import _LazyAutoMapping
from .configuration_auto import (
    CONFIG_MAPPING_NAMES,
    AutoConfig,
    model_type_to_module_name,
    replace_list_option_in_docstrings,
)


SCREAMING_SNAKE_CASE__					=   logging.get_logger(__name__)

SCREAMING_SNAKE_CASE__					=   OrderedDict(
    [
        ("align", "EfficientNetImageProcessor"),
        ("beit", "BeitImageProcessor"),
        ("bit", "BitImageProcessor"),
        ("blip", "BlipImageProcessor"),
        ("blip-2", "BlipImageProcessor"),
        ("bridgetower", "BridgeTowerImageProcessor"),
        ("chinese_clip", "ChineseCLIPImageProcessor"),
        ("clip", "CLIPImageProcessor"),
        ("clipseg", "ViTImageProcessor"),
        ("conditional_detr", "ConditionalDetrImageProcessor"),
        ("convnext", "ConvNextImageProcessor"),
        ("convnextv2", "ConvNextImageProcessor"),
        ("cvt", "ConvNextImageProcessor"),
        ("data2vec-vision", "BeitImageProcessor"),
        ("deformable_detr", "DeformableDetrImageProcessor"),
        ("deit", "DeiTImageProcessor"),
        ("deta", "DetaImageProcessor"),
        ("detr", "DetrImageProcessor"),
        ("dinat", "ViTImageProcessor"),
        ("donut-swin", "DonutImageProcessor"),
        ("dpt", "DPTImageProcessor"),
        ("efficientformer", "EfficientFormerImageProcessor"),
        ("efficientnet", "EfficientNetImageProcessor"),
        ("flava", "FlavaImageProcessor"),
        ("focalnet", "BitImageProcessor"),
        ("git", "CLIPImageProcessor"),
        ("glpn", "GLPNImageProcessor"),
        ("groupvit", "CLIPImageProcessor"),
        ("imagegpt", "ImageGPTImageProcessor"),
        ("instructblip", "BlipImageProcessor"),
        ("layoutlmv2", "LayoutLMv2ImageProcessor"),
        ("layoutlmv3", "LayoutLMv3ImageProcessor"),
        ("levit", "LevitImageProcessor"),
        ("mask2former", "Mask2FormerImageProcessor"),
        ("maskformer", "MaskFormerImageProcessor"),
        ("mgp-str", "ViTImageProcessor"),
        ("mobilenet_v1", "MobileNetV1ImageProcessor"),
        ("mobilenet_v2", "MobileNetV2ImageProcessor"),
        ("mobilevit", "MobileViTImageProcessor"),
        ("mobilevit", "MobileViTImageProcessor"),
        ("mobilevitv2", "MobileViTImageProcessor"),
        ("nat", "ViTImageProcessor"),
        ("oneformer", "OneFormerImageProcessor"),
        ("owlvit", "OwlViTImageProcessor"),
        ("perceiver", "PerceiverImageProcessor"),
        ("pix2struct", "Pix2StructImageProcessor"),
        ("poolformer", "PoolFormerImageProcessor"),
        ("regnet", "ConvNextImageProcessor"),
        ("resnet", "ConvNextImageProcessor"),
        ("sam", "SamImageProcessor"),
        ("segformer", "SegformerImageProcessor"),
        ("swiftformer", "ViTImageProcessor"),
        ("swin", "ViTImageProcessor"),
        ("swin2sr", "Swin2SRImageProcessor"),
        ("swinv2", "ViTImageProcessor"),
        ("table-transformer", "DetrImageProcessor"),
        ("timesformer", "VideoMAEImageProcessor"),
        ("tvlt", "TvltImageProcessor"),
        ("upernet", "SegformerImageProcessor"),
        ("van", "ConvNextImageProcessor"),
        ("videomae", "VideoMAEImageProcessor"),
        ("vilt", "ViltImageProcessor"),
        ("vit", "ViTImageProcessor"),
        ("vit_hybrid", "ViTHybridImageProcessor"),
        ("vit_mae", "ViTImageProcessor"),
        ("vit_msn", "ViTImageProcessor"),
        ("xclip", "CLIPImageProcessor"),
        ("yolos", "YolosImageProcessor"),
    ]
)

SCREAMING_SNAKE_CASE__					=   _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES)


def 			UpperCAmelCase__							(  SCREAMING_SNAKE_CASE     :						str			):







      '''simple docstring'''




      for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items():
            if class_name in extractors:
                  lowerCAmelCase  						=       model_type_to_module_name(SCREAMING_SNAKE_CASE			)

                  lowerCAmelCase  						=       importlib.import_module(F'.{module_name}'							,						"""transformers.models"""			)
                  try:
                        return getattr(SCREAMING_SNAKE_CASE							,						SCREAMING_SNAKE_CASE			)
                  except AttributeError:
                        continue

      for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items():
            if getattr(SCREAMING_SNAKE_CASE							,						"""__name__"""							,						SCREAMING_SNAKE_CASE			) == class_name:
                  return extractor

    # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main
    # init and we return the proper dummy to get an appropriate error message.
      lowerCAmelCase  						=       importlib.import_module("""transformers"""			)
      if hasattr(SCREAMING_SNAKE_CASE							,						SCREAMING_SNAKE_CASE			):
            return getattr(SCREAMING_SNAKE_CASE							,						SCREAMING_SNAKE_CASE			)

      return None


def 			UpperCAmelCase__							(  SCREAMING_SNAKE_CASE     :						Union[str, os.PathLike]							,						SCREAMING_SNAKE_CASE     :						Optional[Union[str, os.PathLike]] = None							,						SCREAMING_SNAKE_CASE     :						bool = False							,						SCREAMING_SNAKE_CASE     :						bool = False							,						SCREAMING_SNAKE_CASE     :						Optional[Dict[str, str]] = None							,						SCREAMING_SNAKE_CASE     :						Optional[Union[bool, str]] = None							,						SCREAMING_SNAKE_CASE     :						Optional[str] = None							,						SCREAMING_SNAKE_CASE     :						bool = False							,						**SCREAMING_SNAKE_CASE     :						List[str]							,						):







      '''simple docstring'''




      lowerCAmelCase  						=       get_file_from_repo(
          SCREAMING_SNAKE_CASE							,						SCREAMING_SNAKE_CASE							,						cache_dir=SCREAMING_SNAKE_CASE							,						force_download=SCREAMING_SNAKE_CASE							,						resume_download=SCREAMING_SNAKE_CASE							,						proxies=SCREAMING_SNAKE_CASE							,						use_auth_token=SCREAMING_SNAKE_CASE							,						revision=SCREAMING_SNAKE_CASE							,						local_files_only=SCREAMING_SNAKE_CASE							,						)
      if resolved_config_file is None:
            logger.info(
                """Could not locate the image processor configuration file, will try to use the model config instead."""			)
            return {}

      with open(SCREAMING_SNAKE_CASE							,						encoding="""utf-8"""			) as reader:
            return json.load(SCREAMING_SNAKE_CASE			)






class 		lowercase					:





      def __init__(       self )		->     str:
            raise EnvironmentError(
                """AutoImageProcessor is designed to be instantiated """
                """using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.""" )





      @classmethod
      @replace_list_option_in_docstrings(lowercase )
      def     _snake_case			(       cls      ,						lowercase      ,						**lowercase )		->     Union[str, Any]:
            lowerCAmelCase  						=       kwargs.pop("""config"""      ,						lowercase )
            lowerCAmelCase  						=       kwargs.pop("""trust_remote_code"""      ,						lowercase )
            lowerCAmelCase  						=       True

            lowerCAmelCase						,		lowerCAmelCase  						=       ImageProcessingMixin.get_image_processor_dict(lowercase      ,						**lowercase )
            lowerCAmelCase  						=       config_dict.get("""image_processor_type"""      ,						lowercase )
            lowerCAmelCase  						=       None
            if "AutoImageProcessor" in config_dict.get("""auto_map"""      ,						{} ):
                  lowerCAmelCase  						=       config_dict["""auto_map"""]["""AutoImageProcessor"""]

            # If we still don't have the image processor class, check if we're loading from a previous feature extractor config
            # and if so, infer the image processor class from there.
            if image_processor_class is None and image_processor_auto_map is None:
                  lowerCAmelCase  						=       config_dict.pop("""feature_extractor_type"""      ,						lowercase )
                  if feature_extractor_class is not None:
                        logger.warning(
                            """Could not find image processor class in the image processor config or the model config. Loading"""
                            """ based on pattern matching with the model's feature extractor configuration.""" )
                        lowerCAmelCase  						=       feature_extractor_class.replace("""FeatureExtractor"""      ,						"""ImageProcessor""" )
                  if "AutoFeatureExtractor" in config_dict.get("""auto_map"""      ,						{} ):
                        lowerCAmelCase  						=       config_dict["""auto_map"""]["""AutoFeatureExtractor"""]
                        lowerCAmelCase  						=       feature_extractor_auto_map.replace("""FeatureExtractor"""      ,						"""ImageProcessor""" )
                        logger.warning(
                            """Could not find image processor auto map in the image processor config or the model config."""
                            """ Loading based on pattern matching with the model's feature extractor configuration.""" )

        # If we don't find the image processor class in the image processor config, let's try the model config.
            if image_processor_class is None and image_processor_auto_map is None:
                  if not isinstance(lowercase      ,						lowercase ):
                        lowerCAmelCase  						=       AutoConfig.from_pretrained(lowercase      ,						**lowercase )
                  # It could be in `config.image_processor_type``
                  lowerCAmelCase  						=       getattr(lowercase      ,						"""image_processor_type"""      ,						lowercase )
                  if hasattr(lowercase      ,						"""auto_map""" ) and "AutoImageProcessor" in config.auto_map:
                        lowerCAmelCase  						=       config.auto_map["""AutoImageProcessor"""]

            if image_processor_class is not None:
                  lowerCAmelCase  						=       image_processor_class_from_name(lowercase )

            lowerCAmelCase  						=       image_processor_auto_map is not None
            lowerCAmelCase  						=       image_processor_class is not None or type(lowercase ) in IMAGE_PROCESSOR_MAPPING
            lowerCAmelCase  						=       resolve_trust_remote_code(
                lowercase      ,						lowercase      ,						lowercase      ,						lowercase )

            if has_remote_code and trust_remote_code:
                  lowerCAmelCase  						=       get_class_from_dynamic_module(
                      lowercase      ,						lowercase      ,						**lowercase )
                  lowerCAmelCase  						=       kwargs.pop("""code_revision"""      ,						lowercase )
                  if os.path.isdir(lowercase ):
                        image_processor_class.register_for_auto_class()
                  return image_processor_class.from_dict(lowercase      ,						**lowercase )
            elif image_processor_class is not None:
                  return image_processor_class.from_dict(lowercase      ,						**lowercase )
            # Last try: we use the IMAGE_PROCESSOR_MAPPING.
            elif type(lowercase ) in IMAGE_PROCESSOR_MAPPING:
                  lowerCAmelCase  						=       IMAGE_PROCESSOR_MAPPING[type(lowercase )]
                  return image_processor_class.from_dict(lowercase      ,						**lowercase )

            raise ValueError(
                f'Unrecognized image processor in {pretrained_model_name_or_path}. Should have a '
                f'`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following '
                f'`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys() )}' )





      @staticmethod
      def     _snake_case			(       lowercase      ,						lowercase )		->     Optional[Any]:
            IMAGE_PROCESSOR_MAPPING.register(lowercase      ,						lowercase )













"""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


SCREAMING_SNAKE_CASE__					=   logging.get_logger(__name__)
SCREAMING_SNAKE_CASE__					=   {"vocab_file": "spiece.model"}

SCREAMING_SNAKE_CASE__					=   {
    "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",
    }
}

SCREAMING_SNAKE_CASE__					=   {
    "AI-Sweden/gpt-sw3-126m": 2_048,
    "AI-Sweden/gpt-sw3-350m": 2_048,
    "AI-Sweden/gpt-sw3-1.6b": 2_048,
    "AI-Sweden/gpt-sw3-6.7b": 2_048,
    "AI-Sweden/gpt-sw3-20b": 2_048,
}

class 		lowercase					(					_UpperCAmelCase					):
      _SCREAMING_SNAKE_CASE					=      VOCAB_FILES_NAMES
      _SCREAMING_SNAKE_CASE					=      PRETRAINED_VOCAB_FILES_MAP
      _SCREAMING_SNAKE_CASE					=      PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      _SCREAMING_SNAKE_CASE					=      ['input_ids', 'attention_mask']





      def __init__(       self      ,						lowercase      ,						lowercase=False      ,						lowercase=False      ,						lowercase=False      ,						lowercase=None      ,						lowercase=None      ,						lowercase=None      ,						lowercase=None      ,						lowercase = None      ,						**lowercase      ,						)		->     None:
            lowerCAmelCase  						=       {} if sp_model_kwargs is None else sp_model_kwargs

            lowerCAmelCase  						=       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""" )
                  lowerCAmelCase  						=       """None"""

            # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing
            lowerCAmelCase  						=       """<|endoftext|>""" if eos_token is None else eos_token
            lowerCAmelCase  						=       """<unk>""" if unk_token is None else unk_token
            if "gpt-sw3-7b" in name_or_path:
                  lowerCAmelCase  						=       unk_token if pad_token is None else pad_token
                  lowerCAmelCase  						=       eos_token if bos_token is None else bos_token
            else:
                  lowerCAmelCase  						=       """<pad>""" if pad_token is None else pad_token
                  lowerCAmelCase  						=       """<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      ,						)

            lowerCAmelCase  						=       do_lower_case
            lowerCAmelCase  						=       remove_space
            lowerCAmelCase  						=       keep_accents
            lowerCAmelCase  						=       vocab_file

            lowerCAmelCase  						=       spm.SentencePieceProcessor(**self.sp_model_kwargs )
            self.sp_model.Load(lowercase )

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

            # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing
            lowerCAmelCase  						=       re.compile(
                f'[{"".join(map(lowercase      ,						list(range(0      ,						9 ) ) + list(range(11      ,						32 ) ) + list(range(127      ,						160 ) ) + [160, 173, 8_203] ) )}]' )





      def __getstate__(       self )		->     Optional[int]:
            lowerCAmelCase  						=       self.__dict__.copy()
            lowerCAmelCase  						=       None
            return state





      def __setstate__(       self      ,						lowercase )		->     str:
            lowerCAmelCase  						=       d

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

            lowerCAmelCase  						=       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     _snake_case			(       self )		->     int:
            return len(self.sp_model )





      def     _snake_case			(       self      ,						lowercase )		->     str:
            lowerCAmelCase  						=       self.non_printing_characters_re.sub(""""""      ,						lowercase )

            # Normalize whitespaces
            lowerCAmelCase  						=       """""".join([char if char not in self.whitespaces else """ """ for char in text] )

            # NFC Unicode normalization
            lowerCAmelCase  						=       unicodedata.normalize("""NFC"""      ,						lowercase )
            return text





      def     _snake_case			(       self      ,						lowercase      ,						**lowercase )		->     List[str]:
            lowerCAmelCase  						=       self.preprocess_text(lowercase )
            return self.sp_model.encode(lowercase      ,						out_type=lowercase )





      def     _snake_case			(       self      ,						lowercase )		->     int:
            return self.sp_model.PieceToId(lowercase )





      def     _snake_case			(       self      ,						lowercase )		->     str:
            return self.sp_model.IdToPiece(lowercase )





      @staticmethod
      def     _snake_case			(       lowercase )		->     str:
            return out_string





      def     _snake_case			(       self      ,						lowercase )		->     str:
            lowerCAmelCase  						=       []
            lowerCAmelCase  						=       """"""
            lowerCAmelCase  						=       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
                        lowerCAmelCase  						=       True
                        lowerCAmelCase  						=       []
                  else:
                        current_sub_tokens.append(lowercase )
                        lowerCAmelCase  						=       False
            out_string += self.sp_model.decode(lowercase )

            return out_string





      def     _snake_case			(       self )		->     Dict[str, int]:
            lowerCAmelCase  						=       {self.convert_ids_to_tokens(lowercase ): i for i in range(self.vocab_size )}
            vocab.update(self.added_tokens_encoder )
            return vocab





      def     _snake_case			(       self      ,						lowercase      ,						lowercase = None )		->     Tuple[str]:
            if not os.path.isdir(lowercase ):
                  logger.error(f'Vocabulary path ({save_directory}) should be a directory' )
                  return
            lowerCAmelCase  						=       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:
                        lowerCAmelCase  						=       self.sp_model.serialized_model_proto()
                        fi.write(lowercase )

            return (out_vocab_file,)





      def     _snake_case			(       self      ,						lowercase      ,						lowercase = False )		->     Union[List[int], List[List[int]], "torch.Tensor"]:

            if isinstance(lowercase      ,						lowercase ):
                  lowerCAmelCase  						=       self.preprocess_text(lowercase )
                  lowerCAmelCase  						=       self.sp_model.encode(lowercase )
            else:
                  lowerCAmelCase  						=       [self.preprocess_text(lowercase ) for t in text]
                  lowerCAmelCase  						=       self.sp_model.encode(lowercase )

            if return_tensors is True or return_tensors == "pt":
                  lowerCAmelCase  						=       torch.tensor(lowercase )

            return token_ids





      def     _snake_case			(       self      ,						lowercase )		->     str:
            return self.sp_model.decode(lowercase )





      def     _snake_case			(       self      ,						lowercase )		->     List[int]:
            lowerCAmelCase  						=       [f'User: {text}' if is_user else f'Bot: {text}' for is_user, text in conversation.iter_texts()]
            lowerCAmelCase  						=       (
                f'{self.eos_token}{self.bos_token}' + f'{self.bos_token}'.join(lowercase ) + f'{self.bos_token}Bot:'
            )
            return self.encode(text=lowercase )






