

'''simple docstring'''




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

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import SPIECE_UNDERLINE, logging


_lowerCAmelCase         =						logging.get_logger(__name__)

_lowerCAmelCase         =						{"vocab_file": "spiece.model"}

_lowerCAmelCase         =						{
    "vocab_file": {
        "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model",
        "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model",
    }
}

_lowerCAmelCase         =						{
    "xlnet-base-cased": None,
    "xlnet-large-cased": None,
}

# Segments (not really needed)
_lowerCAmelCase         =						0
_lowerCAmelCase         =						1
_lowerCAmelCase         =						2
_lowerCAmelCase         =						3
_lowerCAmelCase         =						4






class   _SCREAMING_SNAKE_CASE   (   __a     ):
	__SCREAMING_SNAKE_CASE					:Any      	=					VOCAB_FILES_NAMES
	__SCREAMING_SNAKE_CASE					:Optional[Any]      	=					PRETRAINED_VOCAB_FILES_MAP
	__SCREAMING_SNAKE_CASE					:Optional[Any]      	=					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	__SCREAMING_SNAKE_CASE					:int      	=					'''left'''



	def __init__(   self		:   Tuple			,				a__		:   Optional[Any]			,				a__		:   Optional[int]=False			,				a__		:   int=True			,				a__		:   List[Any]=False			,				a__		:   int="<s>"			,				a__		:   Union[str, Any]="</s>"			,				a__		:   List[str]="<unk>"			,				a__		:   str="<sep>"			,				a__		:   Optional[Any]="<pad>"			,				a__		:   Tuple="<cls>"			,				a__		:   int="<mask>"			,				a__		:   Union[str, Any]=["<eop>", "<eod>"]			,				a__		:   Optional[Dict[str, Any]] = None			,				**a__		:   int			,				):
						__magic_name__						       =    AddedToken(_snake_case			,				lstrip=_snake_case			,				rstrip=_snake_case      ) if isinstance(_snake_case			,				_snake_case      ) else mask_token

						__magic_name__						       =    {} if sp_model_kwargs is None else sp_model_kwargs

						super().__init__(
						    do_lower_case=_snake_case			,				remove_space=_snake_case			,				keep_accents=_snake_case			,				bos_token=_snake_case			,				eos_token=_snake_case			,				unk_token=_snake_case			,				sep_token=_snake_case			,				pad_token=_snake_case			,				cls_token=_snake_case			,				mask_token=_snake_case			,				additional_special_tokens=_snake_case			,				sp_model_kwargs=self.sp_model_kwargs			,				**_snake_case			,				)

						__magic_name__						       =    3

						__magic_name__						       =    do_lower_case
						__magic_name__						       =    remove_space
						__magic_name__						       =    keep_accents
						__magic_name__						       =    vocab_file

						__magic_name__						       =    spm.SentencePieceProcessor(**self.sp_model_kwargs      )
						self.sp_model.Load(_snake_case      )



	@property
	def 			snake_case__  (   self		:   Tuple      ):
						return len(self.sp_model      )



	def 			snake_case__  (   self		:   Union[str, Any]      ):
						__magic_name__						       =    {self.convert_ids_to_tokens(_snake_case      ): i for i in range(self.vocab_size      )}
						vocab.update(self.added_tokens_encoder      )
						return vocab



	def __getstate__(   self		:   Any      ):
						__magic_name__						       =    self.__dict__.copy()
						__magic_name__						       =    None
						return state



	def __setstate__(   self		:   str			,				a__		:   Union[str, Any]      ):
						__magic_name__						       =    d

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

						__magic_name__						       =    spm.SentencePieceProcessor(**self.sp_model_kwargs      )
						self.sp_model.Load(self.vocab_file      )



	def 			snake_case__  (   self		:   int			,				a__		:   Any      ):


						if self.remove_space:
											__magic_name__						       =    ''' '''.join(inputs.strip().split()      )
						else:
											__magic_name__						       =    inputs
						__magic_name__						       =    outputs.replace('''``'''			,				'''"'''      ).replace('''\'\''''			,				'''"'''      )

						if not self.keep_accents:
											__magic_name__						       =    unicodedata.normalize('''NFKD'''			,				_snake_case      )
											__magic_name__						       =    ''''''.join([c for c in outputs if not unicodedata.combining(_snake_case      )]      )
						if self.do_lower_case:
											__magic_name__						       =    outputs.lower()

						return outputs



	def 			snake_case__  (   self		:   Any			,				a__		:   str      ):
						__magic_name__						       =    self.preprocess_text(_snake_case      )
						__magic_name__						       =    self.sp_model.encode(_snake_case			,				out_type=_snake_case      )
						__magic_name__						       =    []
						for piece in pieces:
											if len(_snake_case      ) > 1 and piece[-1] == str(''','''      ) and piece[-2].isdigit():
																__magic_name__						       =    self.sp_model.EncodeAsPieces(piece[:-1].replace(_snake_case			,				''''''      )      )
																if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
																					if len(cur_pieces[0]      ) == 1:
																										__magic_name__						       =    cur_pieces[1:]
																					else:
																										__magic_name__						       =    cur_pieces[0][1:]
																cur_pieces.append(piece[-1]      )
																new_pieces.extend(_snake_case      )
											else:
																new_pieces.append(_snake_case      )

						return new_pieces



	def 			snake_case__  (   self		:   Tuple			,				a__		:   Dict      ):
						return self.sp_model.PieceToId(_snake_case      )



	def 			snake_case__  (   self		:   str			,				a__		:   Union[str, Any]      ):
						return self.sp_model.IdToPiece(_snake_case      )



	def 			snake_case__  (   self		:   List[Any]			,				a__		:   Optional[Any]      ):
						__magic_name__						       =    ''''''.join(_snake_case      ).replace(_snake_case			,				''' '''      ).strip()
						return out_string



	def 			snake_case__  (   self		:   Any			,				a__		:   List[int]			,				a__		:   bool = False			,				a__		:   bool = None			,				a__		:   bool = True			,				**a__		:   Dict			,				):
						__magic_name__						       =    kwargs.pop('''use_source_tokenizer'''			,				_snake_case      )

						__magic_name__						       =    self.convert_ids_to_tokens(_snake_case			,				skip_special_tokens=_snake_case      )

						# To avoid mixing byte-level and unicode for byte-level BPT
						# we need to build string separately for added tokens and byte-level tokens
						# cf. https://github.com/huggingface/transformers/issues/1133
						__magic_name__						       =    []
						__magic_name__						       =    []
						for token in filtered_tokens:
											if skip_special_tokens and token in self.all_special_ids:
																continue
											if token in self.added_tokens_encoder:
																if current_sub_text:
																					sub_texts.append(self.convert_tokens_to_string(_snake_case      )      )
																					__magic_name__						       =    []
																sub_texts.append(_snake_case      )
											else:
																current_sub_text.append(_snake_case      )
						if current_sub_text:
											sub_texts.append(self.convert_tokens_to_string(_snake_case      )      )

						# Mimic the behavior of the Rust tokenizer:
						# By default, there are no spaces between special tokens
						__magic_name__						       =    ''''''.join(_snake_case      )

						__magic_name__						       =    (
						    clean_up_tokenization_spaces
						    if clean_up_tokenization_spaces is not None
						    else self.clean_up_tokenization_spaces
						)
						if clean_up_tokenization_spaces:
											__magic_name__						       =    self.clean_up_tokenization(_snake_case      )
											return clean_text
						else:
											return text



	def 			snake_case__  (   self		:   Dict			,				a__		:   List[int]			,				a__		:   Optional[List[int]] = None      ):
						__magic_name__						       =    [self.sep_token_id]
						__magic_name__						       =    [self.cls_token_id]
						if token_ids_a is None:
											return token_ids_a + sep + cls
						return token_ids_a + sep + token_ids_a + sep + cls



	def 			snake_case__  (   self		:   Tuple			,				a__		:   List[int]			,				a__		:   Optional[List[int]] = None			,				a__		:   bool = False      ):


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

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



	def 			snake_case__  (   self		:   Any			,				a__		:   List[int]			,				a__		:   Optional[List[int]] = None      ):
						__magic_name__						       =    [self.sep_token_id]
						__magic_name__						       =    [2]

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



	def 			snake_case__  (   self		:   Tuple			,				a__		:   str			,				a__		:   Optional[str] = None      ):


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

						if os.path.abspath(self.vocab_file      ) != os.path.abspath(_snake_case      ) and os.path.isfile(self.vocab_file      ):
											copyfile(self.vocab_file			,				_snake_case      )
						elif not os.path.isfile(self.vocab_file      ):
											with open(_snake_case			,				'''wb'''      ) as fi:
																__magic_name__						       =    self.sp_model.serialized_model_proto()
																fi.write(_snake_case      )

						return (out_vocab_file,)









'''simple docstring'''




import importlib
import inspect
import json
import os
import re
import shutil
import sys
from pathlib import Path
from typing import Dict, Optional, Union
from urllib import request

from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info
from packaging import version

from .. import __version__
from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging


_lowerCAmelCase         =						(
    "https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py"
)


_lowerCAmelCase         =						logging.get_logger(__name__)  # pylint: disable=invalid-name




def 						UpperCamelCase	(			)				->     Optional[Any]:






     '''simple docstring'''
     __magic_name__						       =    '''https://pypi.org/pypi/diffusers/json'''
     __magic_name__						       =    json.loads(request.urlopen(a			).read()			)['''releases'''].keys()
     return sorted(a		,						key=lambda a			: version.Version(a			)			)




def 						UpperCamelCase	(			)				->     Any:






     '''simple docstring'''
     # This function has already been executed if HF_MODULES_CACHE already is in the Python path.
     if HF_MODULES_CACHE in sys.path:
          return

     sys.path.append(a			)
     os.makedirs(a		,						exist_ok=a			)
     __magic_name__						       =    Path(a			) / '''__init__.py'''
     if not init_path.exists():
          init_path.touch()




def 						UpperCamelCase	(			a			)				->     Tuple:






     '''simple docstring'''
     init_hf_modules()
     __magic_name__						       =    Path(a			) / name
     # If the parent module does not exist yet, recursively create it.
     if not dynamic_module_path.parent.exists():
          create_dynamic_module(dynamic_module_path.parent			)
     os.makedirs(a		,						exist_ok=a			)
     __magic_name__						       =    dynamic_module_path / '''__init__.py'''
     if not init_path.exists():
          init_path.touch()




def 						UpperCamelCase	(			a			)				->     List[str]:






     '''simple docstring'''
     with open(a		,						'''r'''		,						encoding='''utf-8'''			) as f:
          __magic_name__						       =    f.read()

     # Imports of the form `import .xxx`
     __magic_name__						       =    re.findall('''^\s*import\s+\.(\S+)\s*$'''		,						a		,						flags=re.MULTILINE			)
     # Imports of the form `from .xxx import yyy`
     relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import'''		,						a		,						flags=re.MULTILINE			)
     # Unique-ify
     return list(set(a			)			)




def 						UpperCamelCase	(			a			)				->     str:






     '''simple docstring'''
     __magic_name__						       =    False
     __magic_name__						       =    [module_file]
     __magic_name__						       =    []

     # Let's recurse through all relative imports
     while not no_change:
          __magic_name__						       =    []
          for f in files_to_check:
               new_imports.extend(get_relative_imports(a			)			)

          __magic_name__						       =    Path(a			).parent
          __magic_name__						       =    [str(module_path / m			) for m in new_imports]
          __magic_name__						       =    [f for f in new_import_files if f not in all_relative_imports]
          __magic_name__						       =    [F'''{f}.py''' for f in new_import_files]

          __magic_name__						       =    len(a			) == 0
          all_relative_imports.extend(a			)

     return all_relative_imports




def 						UpperCamelCase	(			a			)				->     List[str]:






     '''simple docstring'''
     with open(a		,						'''r'''		,						encoding='''utf-8'''			) as f:
          __magic_name__						       =    f.read()

     # Imports of the form `import xxx`
     __magic_name__						       =    re.findall('''^\s*import\s+(\S+)\s*$'''		,						a		,						flags=re.MULTILINE			)
     # Imports of the form `from xxx import yyy`
     imports += re.findall('''^\s*from\s+(\S+)\s+import'''		,						a		,						flags=re.MULTILINE			)
     # Only keep the top-level module
     __magic_name__						       =    [imp.split('''.'''			)[0] for imp in imports if not imp.startswith('''.'''			)]

     # Unique-ify and test we got them all
     __magic_name__						       =    list(set(a			)			)
     __magic_name__						       =    []
     for imp in imports:
          try:
               importlib.import_module(a			)
          except ImportError:
               missing_packages.append(a			)

     if len(a			) > 0:
          raise ImportError(
              '''This modeling file requires the following packages that were not found in your environment: '''
              F'''{", ".join(a			)}. Run `pip install {" ".join(a			)}`'''			)

     return get_relative_imports(a			)




def 						UpperCamelCase	(			a		,						a			)				->     Optional[int]:






     '''simple docstring'''
     __magic_name__						       =    module_path.replace(os.path.sep		,						'''.'''			)
     __magic_name__						       =    importlib.import_module(a			)

     if class_name is None:
          return find_pipeline_class(a			)
     return getattr(a		,						a			)




def 						UpperCamelCase	(			a			)				->     Tuple:






     '''simple docstring'''
     from ..pipelines import DiffusionPipeline

     __magic_name__						       =    dict(inspect.getmembers(a		,						inspect.isclass			)			)

     __magic_name__						       =    None
     for cls_name, cls in cls_members.items():
          if (
              cls_name != DiffusionPipeline.__name__
              and issubclass(cls		,						a			)
              and cls.__module__.split('''.'''			)[0] != "diffusers"
          ):
               if pipeline_class is not None:
                    raise ValueError(
                        F'''Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:'''
                        F''' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in'''
                        F''' {loaded_module}.'''			)
               __magic_name__						       =    cls

     return pipeline_class




def 						UpperCamelCase	(			a		,						a		,						a = None		,						a = False		,						a = False		,						a = None		,						a = None		,						a = None		,						a = False		,						)				->     List[Any]:






     '''simple docstring'''
     __magic_name__						       =    str(a			)

     __magic_name__						       =    os.path.join(a		,						a			)

     if os.path.isfile(a			):
          __magic_name__						       =    module_file_or_url
          __magic_name__						       =    '''local'''
     elif pretrained_model_name_or_path.count('''/'''			) == 0:
          __magic_name__						       =    get_diffusers_versions()
          # cut ".dev0"
          __magic_name__						       =    '''v''' + '''.'''.join(__version__.split('''.'''			)[:3]			)

          # retrieve github version that matches
          if revision is None:
               __magic_name__						       =    latest_version if latest_version[1:] in available_versions else '''main'''
               logger.info(F'''Defaulting to latest_version: {revision}.'''			)
          elif revision in available_versions:
               __magic_name__						       =    F'''v{revision}'''
          elif revision == "main":
               __magic_name__						       =    revision
          else:
               raise ValueError(
                   F'''`custom_revision`: {revision} does not exist. Please make sure to choose one of'''
                   F''' {", ".join(available_versions + ["main"]			)}.'''			)

          # community pipeline on GitHub
          __magic_name__						       =    COMMUNITY_PIPELINES_URL.format(revision=a		,						pipeline=a			)
          try:
               __magic_name__						       =    cached_download(
                   a		,						cache_dir=a		,						force_download=a		,						proxies=a		,						resume_download=a		,						local_files_only=a		,						use_auth_token=a		,						)
               __magic_name__						       =    '''git'''
               __magic_name__						       =    pretrained_model_name_or_path + '''.py'''
          except EnvironmentError:
               logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.'''			)
               raise
     else:
          try:
               # Load from URL or cache if already cached
               __magic_name__						       =    hf_hub_download(
                   a		,						a		,						cache_dir=a		,						force_download=a		,						proxies=a		,						resume_download=a		,						local_files_only=a		,						use_auth_token=a		,						)
               __magic_name__						       =    os.path.join('''local'''		,						'''--'''.join(pretrained_model_name_or_path.split('''/'''			)			)			)
          except EnvironmentError:
               logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.'''			)
               raise

    # Check we have all the requirements in our environment
     __magic_name__						       =    check_imports(a			)

     # Now we move the module inside our cached dynamic modules.
     __magic_name__						       =    DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule
     create_dynamic_module(a			)
     __magic_name__						       =    Path(a			) / full_submodule
     if submodule == "local" or submodule == "git":
          # We always copy local files (we could hash the file to see if there was a change, and give them the name of
          # that hash, to only copy when there is a modification but it seems overkill for now).
          # The only reason we do the copy is to avoid putting too many folders in sys.path.
          shutil.copy(a		,						submodule_path / module_file			)
          for module_needed in modules_needed:
               __magic_name__						       =    F'''{module_needed}.py'''
               shutil.copy(os.path.join(a		,						a			)		,						submodule_path / module_needed			)
     else:
          # Get the commit hash
          # TODO: we will get this info in the etag soon, so retrieve it from there and not here.
          if isinstance(a		,						a			):
               __magic_name__						       =    use_auth_token
          elif use_auth_token is True:
               __magic_name__						       =    HfFolder.get_token()
          else:
               __magic_name__						       =    None

          __magic_name__						       =    model_info(a		,						revision=a		,						token=a			).sha

          # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the
          # benefit of versioning.
          __magic_name__						       =    submodule_path / commit_hash
          __magic_name__						       =    full_submodule + os.path.sep + commit_hash
          create_dynamic_module(a			)

          if not (submodule_path / module_file).exists():
               shutil.copy(a		,						submodule_path / module_file			)
          # Make sure we also have every file with relative
          for module_needed in modules_needed:
               if not (submodule_path / module_needed).exists():
                    get_cached_module_file(
                        a		,						F'''{module_needed}.py'''		,						cache_dir=a		,						force_download=a		,						resume_download=a		,						proxies=a		,						use_auth_token=a		,						revision=a		,						local_files_only=a		,						)
     return os.path.join(a		,						a			)




def 						UpperCamelCase	(			a		,						a		,						a = None		,						a = None		,						a = False		,						a = False		,						a = None		,						a = None		,						a = None		,						a = False		,						**a		,						)				->     List[Any]:






     '''simple docstring'''
     __magic_name__						       =    get_cached_module_file(
         a		,						a		,						cache_dir=a		,						force_download=a		,						resume_download=a		,						proxies=a		,						use_auth_token=a		,						revision=a		,						local_files_only=a		,						)
     return get_class_in_module(a		,						final_module.replace('''.py'''		,						''''''			)			)






