


'''simple docstring'''

import os
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 logging


lowerCamelCase							:   List[str]  						=	logging.get_logger(__name__)

lowerCamelCase							:   Dict  						=	'▁'

lowerCamelCase							:   List[str]  						=	{'vocab_file': 'sentencepiece.bpe.model', 'monolingual_vocab_file': 'dict.txt'}

lowerCamelCase							:   Union[str, Any]  						=	{
    'vocab_file': {
        'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model',
    },
    'monolingual_vocab_file': {
        'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt',
    },
}

lowerCamelCase							:   int  						=	{'vinai/bartpho-syllable': 1_024}
class   __lowerCAmelCase						(_lowerCAmelCase     ):





      '''simple docstring'''






      lowerCAmelCase__					:     str  					=							VOCAB_FILES_NAMES
      lowerCAmelCase__					:     Optional[int]  					=							PRETRAINED_VOCAB_FILES_MAP
      lowerCAmelCase__					:     Optional[int]  					=							PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      lowerCAmelCase__					:     Tuple  					=							["input_ids", "attention_mask"]



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

             '''simple docstring'''







             lowercase__      			= AddedToken(_lowerCamelCase   ,						lstrip=_lowerCamelCase   ,						rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase   ,						_lowerCamelCase ) else mask_token

             lowercase__      			= {} if sp_model_kwargs is None else sp_model_kwargs

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

             lowercase__      			= vocab_file
             lowercase__      			= monolingual_vocab_file
             lowercase__      			= spm.SentencePieceProcessor(**self.sp_model_kwargs )
             self.sp_model.Load(str(_lowerCamelCase ) )

             # Load the reduced vocab

             # Keep order of special tokens for backward compatibility
             lowercase__      			= {}
             lowercase__      			= 0
             for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]:
                    if str(_lowerCamelCase ) not in self.fairseq_tokens_to_ids:
                           lowercase__      			= cnt
                           cnt += 1
             with open(_lowerCamelCase   ,						'''r'''   ,						encoding='''utf-8''' ) as f:
                    for line in f.readlines():
                           lowercase__      			= line.strip().split()[0]
                           lowercase__      			= len(self.fairseq_tokens_to_ids )
             if str(_lowerCamelCase ) not in self.fairseq_tokens_to_ids:
                    lowercase__      			= len(self.fairseq_tokens_to_ids )

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



      def __getstate__(self    :    Union[str, Any] ):

             '''simple docstring'''







             lowercase__      			= self.__dict__.copy()
             lowercase__      			= None
             lowercase__      			= self.sp_model.serialized_model_proto()
             return state



      def __setstate__(self    :    Union[str, Any]   ,						UpperCamelCase    :    Dict ):

             '''simple docstring'''







             lowercase__      			= d

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

             lowercase__      			= spm.SentencePieceProcessor(**self.sp_model_kwargs )
             self.sp_model.LoadFromSerializedProto(self.sp_model_proto )



      def       UpperCamelCase__		(self    :    Any   ,						UpperCamelCase    :    List[int]   ,						UpperCamelCase    :    Optional[List[int]] = None ):

             '''simple docstring'''







             if token_ids_a is None:
                    return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
             lowercase__      			= [self.cls_token_id]
             lowercase__      			= [self.sep_token_id]
             return cls + token_ids_a + sep + sep + token_ids_a + sep



      def       UpperCamelCase__		(self    :    List[str]   ,						UpperCamelCase    :    List[int]   ,						UpperCamelCase    :    Optional[List[int]] = None   ,						UpperCamelCase    :    bool = False ):

             '''simple docstring'''







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

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



      def       UpperCamelCase__		(self    :    Dict   ,						UpperCamelCase    :    List[int]   ,						UpperCamelCase    :    Optional[List[int]] = None ):

             '''simple docstring'''







             lowercase__      			= [self.sep_token_id]
             lowercase__      			= [self.cls_token_id]

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



      @property
      def       UpperCamelCase__		(self    :    Optional[int] ):

             '''simple docstring'''







             return len(self.fairseq_ids_to_tokens )



      def       UpperCamelCase__		(self    :    int ):

             '''simple docstring'''







             lowercase__      			= {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )}
             vocab.update(self.added_tokens_encoder )
             return vocab



      def       UpperCamelCase__		(self    :    Any   ,						UpperCamelCase    :    str ):

             '''simple docstring'''







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



      def       UpperCamelCase__		(self    :    List[Any]   ,						UpperCamelCase    :    List[Any] ):

             '''simple docstring'''







             if token in self.fairseq_tokens_to_ids:
                    return self.fairseq_tokens_to_ids[token]
             else:
                    return self.unk_token_id



      def       UpperCamelCase__		(self    :    Dict   ,						UpperCamelCase    :    Optional[int] ):

             '''simple docstring'''







             return self.fairseq_ids_to_tokens[index]



      def       UpperCamelCase__		(self    :    Optional[Any]   ,						UpperCamelCase    :    Union[str, Any] ):

             '''simple docstring'''







             lowercase__      			= ''''''.join(_lowerCamelCase ).replace(_lowerCamelCase   ,						''' ''' ).strip()
             return out_string






      def       UpperCamelCase__		(self    :    List[Any]   ,						UpperCamelCase    :    str   ,						UpperCamelCase    :    Optional[str] = None ):

             '''simple docstring'''







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

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

             if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath(
                 _lowerCamelCase ) and os.path.isfile(self.monolingual_vocab_file ):
                    copyfile(self.monolingual_vocab_file   ,						_lowerCamelCase )
             elif not os.path.isfile(self.monolingual_vocab_file ):
                    with open(_lowerCamelCase   ,						'''w'''   ,						encoding='''utf-8''' ) as fp:
                           for token in self.fairseq_tokens_to_ids:
                                  if token not in self.all_special_tokens:
                                         fp.write(f"{str(_lowerCamelCase )} \n" )

             return out_vocab_file, out_monolingual_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


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


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



def 					lowerCAmelCase				(    ):




  """simple docstring"""







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



def 					lowerCAmelCase				(    ):




  """simple docstring"""







  if HF_MODULES_CACHE in sys.path:
    return

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



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  init_hf_modules()
  __A									= Path(__UpperCamelCase ) / 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(__UpperCamelCase		,       exist_ok=__UpperCamelCase )
  __A									= dynamic_module_path / '''__init__.py'''
  if not init_path.exists():
    init_path.touch()



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  with open(__UpperCamelCase		,       '''r'''		,       encoding='''utf-8''' ) as f:
    __A									= f.read()

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



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  __A									= False
  __A									= [module_file]
  __A									= []

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

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

    __A									= len(__UpperCamelCase ) == 0
    all_relative_imports.extend(__UpperCamelCase )

  return all_relative_imports



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  with open(__UpperCamelCase		,       '''r'''		,       encoding='''utf-8''' ) as f:
    __A									= f.read()

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

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

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

  return get_relative_imports(__UpperCamelCase )



def 					lowerCAmelCase				(    __UpperCamelCase		,       __UpperCamelCase ):




  """simple docstring"""







  __A									= module_path.replace(os.path.sep		,       '''.''' )
  __A									= importlib.import_module(__UpperCamelCase )

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



def 					lowerCAmelCase				(    __UpperCamelCase ):




  """simple docstring"""







  from ..pipelines import DiffusionPipeline

  __A									= dict(inspect.getmembers(__UpperCamelCase		,       inspect.isclass ) )

  __A									= None
  for cls_name, cls in cls_members.items():
    if (
        cls_name != DiffusionPipeline.__name__
        and issubclass(cls		,       __UpperCamelCase )
        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}.' )
      __A									= cls

  return pipeline_class



def 					lowerCAmelCase				(    __UpperCamelCase		,       __UpperCamelCase		,       __UpperCamelCase = None		,       __UpperCamelCase = False		,       __UpperCamelCase = False		,       __UpperCamelCase = None		,       __UpperCamelCase = None		,       __UpperCamelCase = None		,       __UpperCamelCase = False		,       ):




  """simple docstring"""







  __A									= str(__UpperCamelCase )

  __A									= os.path.join(__UpperCamelCase		,       __UpperCamelCase )

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

    # retrieve github version that matches
    if revision is None:
      __A									= latest_version if latest_version[1:] in available_versions else '''main'''
      logger.info(f'Defaulting to latest_version: {revision}.' )
    elif revision in available_versions:
      __A									= f'v{revision}'
    elif revision == "main":
      __A									= 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
    __A									= COMMUNITY_PIPELINES_URL.format(revision=__UpperCamelCase		,       pipeline=__UpperCamelCase )
    try:
      __A									= cached_download(
          __UpperCamelCase		,       cache_dir=__UpperCamelCase		,       force_download=__UpperCamelCase		,       proxies=__UpperCamelCase		,       resume_download=__UpperCamelCase		,       local_files_only=__UpperCamelCase		,       use_auth_token=__UpperCamelCase		,       )
      __A									= '''git'''
      __A									= 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
      __A									= hf_hub_download(
          __UpperCamelCase		,       __UpperCamelCase		,       cache_dir=__UpperCamelCase		,       force_download=__UpperCamelCase		,       proxies=__UpperCamelCase		,       resume_download=__UpperCamelCase		,       local_files_only=__UpperCamelCase		,       use_auth_token=__UpperCamelCase		,       )
      __A									= 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
  __A									= check_imports(__UpperCamelCase )

  # Now we move the module inside our cached dynamic modules.
  __A									= DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule
  create_dynamic_module(__UpperCamelCase )
  __A									= Path(__UpperCamelCase ) / 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(__UpperCamelCase		,       submodule_path / module_file )
    for module_needed in modules_needed:
      __A									= f'{module_needed}.py'
      shutil.copy(os.path.join(__UpperCamelCase		,       __UpperCamelCase )		,       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(__UpperCamelCase		,       __UpperCamelCase ):
      __A									= use_auth_token
    elif use_auth_token is True:
      __A									= HfFolder.get_token()
    else:
      __A									= None

    __A									= model_info(__UpperCamelCase		,       revision=__UpperCamelCase		,       token=__UpperCamelCase ).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.
    __A									= submodule_path / commit_hash
    __A									= full_submodule + os.path.sep + commit_hash
    create_dynamic_module(__UpperCamelCase )

    if not (submodule_path / module_file).exists():
      shutil.copy(__UpperCamelCase		,       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(
            __UpperCamelCase		,       f'{module_needed}.py'		,       cache_dir=__UpperCamelCase		,       force_download=__UpperCamelCase		,       resume_download=__UpperCamelCase		,       proxies=__UpperCamelCase		,       use_auth_token=__UpperCamelCase		,       revision=__UpperCamelCase		,       local_files_only=__UpperCamelCase		,       )
  return os.path.join(__UpperCamelCase		,       __UpperCamelCase )





def 					lowerCAmelCase				(    __UpperCamelCase		,       __UpperCamelCase		,       __UpperCamelCase = None		,       __UpperCamelCase = None		,       __UpperCamelCase = False		,       __UpperCamelCase = False		,       __UpperCamelCase = None		,       __UpperCamelCase = None		,       __UpperCamelCase = None		,       __UpperCamelCase = False		,       **__UpperCamelCase		,       ):




  """simple docstring"""







  __A									= get_cached_module_file(
      __UpperCamelCase		,       __UpperCamelCase		,       cache_dir=__UpperCamelCase		,       force_download=__UpperCamelCase		,       resume_download=__UpperCamelCase		,       proxies=__UpperCamelCase		,       use_auth_token=__UpperCamelCase		,       revision=__UpperCamelCase		,       local_files_only=__UpperCamelCase		,       )
  return get_class_in_module(__UpperCamelCase		,       final_module.replace('''.py'''		,       '''''' ) )




