





"""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_     :						Any						=					(
    'https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py'
)


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





def 						UpperCAmelCase__		(     ):






  """simple docstring"""





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





def 						UpperCAmelCase__		(     ):






  """simple docstring"""





  if HF_MODULES_CACHE in sys.path:
    return

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





def 						UpperCAmelCase__		(     _UpperCAmelCase					):






  """simple docstring"""





  init_hf_modules()
  A_  :       Dict										=  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_  :       Tuple										=  dynamic_module_path / '__init__.py'
  if not init_path.exists():
    init_path.touch()





def 						UpperCAmelCase__		(     _UpperCAmelCase					):






  """simple docstring"""





  with open(_UpperCAmelCase ,					'r' ,					encoding='utf-8'					) as f:
    A_  :       Optional[Any]										=  f.read()

  # Imports of the form `import .xxx`
  A_  :       Optional[int]										=  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 						UpperCAmelCase__		(     _UpperCAmelCase					):






  """simple docstring"""





  A_  :       Any										=  False
  A_  :       Dict										=  [module_file]
  A_  :       Dict										=  []

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

    A_  :       int										=  Path(_UpperCAmelCase					).parent
    A_  :       Tuple										=  [str(module_path / m					) for m in new_imports]
    A_  :       str										=  [f for f in new_import_files if f not in all_relative_imports]
    A_  :       int										=  [f"""{f}.py""" for f in new_import_files]

    A_  :       Optional[Any]										=  len(_UpperCAmelCase					) == 0
    all_relative_imports.extend(_UpperCAmelCase					)

  return all_relative_imports





def 						UpperCAmelCase__		(     _UpperCAmelCase					):






  """simple docstring"""





  with open(_UpperCAmelCase ,					'r' ,					encoding='utf-8'					) as f:
    A_  :       Any										=  f.read()

  # Imports of the form `import xxx`
  A_  :       Any										=  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_  :       Any										=  [imp.split('.'					)[0] for imp in imports if not imp.startswith('.'					)]

  # Unique-ify and test we got them all
  A_  :       List[Any]										=  list(set(_UpperCAmelCase					)					)
  A_  :       Any										=  []
  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 						UpperCAmelCase__		(     _UpperCAmelCase ,					_UpperCAmelCase					):






  """simple docstring"""





  A_  :       Any										=  module_path.replace(os.path.sep ,					'.'					)
  A_  :       int										=  importlib.import_module(_UpperCAmelCase					)

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





def 						UpperCAmelCase__		(     _UpperCAmelCase					):






  """simple docstring"""





  from ..pipelines import DiffusionPipeline

  A_  :       int										=  dict(inspect.getmembers(_UpperCAmelCase ,					inspect.isclass					)					)

  A_  :       List[str]										=  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_  :       Union[str, Any]										=  cls

  return pipeline_class





def 						UpperCAmelCase__		(     _UpperCAmelCase ,					_UpperCAmelCase ,					_UpperCAmelCase = None ,					_UpperCAmelCase = False ,					_UpperCAmelCase = False ,					_UpperCAmelCase = None ,					_UpperCAmelCase = None ,					_UpperCAmelCase = None ,					_UpperCAmelCase = False ,					):






  """simple docstring"""





  A_  :       int										=  str(_UpperCAmelCase					)

  A_  :       Optional[int]										=  os.path.join(_UpperCAmelCase ,					_UpperCAmelCase					)

  if os.path.isfile(_UpperCAmelCase					):
    A_  :       List[str]										=  module_file_or_url
    A_  :       Union[str, Any]										=  'local'
  elif pretrained_model_name_or_path.count('/'					) == 0:
    A_  :       Union[str, Any]										=  get_diffusers_versions()
    # cut ".dev0"
    A_  :       Optional[Any]										=  'v' + '.'.join(__version__.split('.'					)[:3]					)

    # retrieve github version that matches
    if revision is None:
      A_  :       List[Any]										=  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_  :       Optional[int]										=  f"""v{revision}"""
    elif revision == "main":
      A_  :       Union[str, Any]										=  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_  :       List[Any]										=  COMMUNITY_PIPELINES_URL.format(revision=_UpperCAmelCase ,					pipeline=_UpperCAmelCase					)
    try:
      A_  :       Dict										=  cached_download(
          _UpperCAmelCase ,					cache_dir=_UpperCAmelCase ,					force_download=_UpperCAmelCase ,					proxies=_UpperCAmelCase ,					resume_download=_UpperCAmelCase ,					local_files_only=_UpperCAmelCase ,					use_auth_token=_UpperCAmelCase ,					)
      A_  :       Optional[int]										=  'git'
      A_  :       Optional[Any]										=  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_  :       Optional[Any]										=  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_  :       str										=  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_  :       Optional[int]										=  check_imports(_UpperCAmelCase					)

  # Now we move the module inside our cached dynamic modules.
  A_  :       str										=  DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule
  create_dynamic_module(_UpperCAmelCase					)
  A_  :       Optional[Any]										=  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_  :       Tuple										=  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_  :       Union[str, Any]										=  use_auth_token
    elif use_auth_token is True:
      A_  :       List[Any]										=  HfFolder.get_token()
    else:
      A_  :       Dict										=  None

    A_  :       List[Any]										=  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_  :       Optional[Any]										=  submodule_path / commit_hash
    A_  :       List[Any]										=  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 						UpperCAmelCase__		(     _UpperCAmelCase ,					_UpperCAmelCase ,					_UpperCAmelCase = None ,					_UpperCAmelCase = None ,					_UpperCAmelCase = False ,					_UpperCAmelCase = False ,					_UpperCAmelCase = None ,					_UpperCAmelCase = None ,					_UpperCAmelCase = None ,					_UpperCAmelCase = False ,					**_UpperCAmelCase ,					):






  """simple docstring"""





  A_  :       Optional[Any]										=  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' ,					''					)					)






"""simple docstring"""




import copy
import random

from transformers import CLIPTokenizer

class  _UpperCAmelCase  (   UpperCAmelCase__		):



      '''simple docstring'''

      def __init__(     self					,      *snake_case_					,      **snake_case_  ):

        """simple docstring"""

        super().__init__(*snake_case_					,      **snake_case_  )
        A_  :       Tuple										=  {}

      def 					lowerCamelCase_			(     self					,      snake_case_					,      *snake_case_					,      **snake_case_  ):

        """simple docstring"""

        A_  :       str										=  super().add_tokens(snake_case_					,      *snake_case_					,      **snake_case_  )
        if num_added_tokens == 0:
          raise ValueError(
              F"""The tokenizer already contains the token {placeholder_token}. Please pass a different"""
              ' `placeholder_token` that is not already in the tokenizer.'  )

      def 					lowerCamelCase_			(     self					,      snake_case_					,      *snake_case_					,      snake_case_=1					,      **snake_case_  ):

        """simple docstring"""

        A_  :       Tuple										=  []
        if num_vec_per_token == 1:
          self.try_adding_tokens(snake_case_					,      *snake_case_					,      **snake_case_  )
          output.append(snake_case_  )
        else:
          A_  :       Tuple										=  []
          for i in range(snake_case_  ):
            A_  :       List[str]										=  placeholder_token + F"""_{i}"""
            self.try_adding_tokens(snake_case_					,      *snake_case_					,      **snake_case_  )
            output.append(snake_case_  )
        # handle cases where there is a new placeholder token that contains the current placeholder token but is larger
        for token in self.token_map:
          if token in placeholder_token:
            raise ValueError(
                F"""The tokenizer already has placeholder token {token} that can get confused with"""
                F""" {placeholder_token}keep placeholder tokens independent"""  )
        A_  :       Any										=  output

      def 					lowerCamelCase_			(     self					,      snake_case_					,      snake_case_=False					,      snake_case_=1.0  ):

        """simple docstring"""

        if isinstance(snake_case_					,      snake_case_  ):
          A_  :       Optional[Any]										=  []
          for i in range(len(snake_case_  )  ):
            output.append(self.replace_placeholder_tokens_in_text(text[i]					,      vector_shuffle=snake_case_  )  )
          return output
        for placeholder_token in self.token_map:
          if placeholder_token in text:
            A_  :       List[Any]										=  self.token_map[placeholder_token]
            A_  :       Optional[int]										=  tokens[: 1 + int(len(snake_case_  ) * prop_tokens_to_load  )]
            if vector_shuffle:
              A_  :       Optional[Any]										=  copy.copy(snake_case_  )
              random.shuffle(snake_case_  )
            A_  :       List[str]										=  text.replace(snake_case_					,      ' '.join(snake_case_  )  )
        return text

      def __call__(     self					,      snake_case_					,      *snake_case_					,      snake_case_=False					,      snake_case_=1.0					,      **snake_case_  ):

        """simple docstring"""

        return super().__call__(
            self.replace_placeholder_tokens_in_text(
                snake_case_					,      vector_shuffle=snake_case_					,      prop_tokens_to_load=snake_case_  )					,      *snake_case_					,      **snake_case_					,      )

      def 					lowerCamelCase_			(     self					,      snake_case_					,      *snake_case_					,      snake_case_=False					,      snake_case_=1.0					,      **snake_case_  ):

        """simple docstring"""

        return super().encode(
            self.replace_placeholder_tokens_in_text(
                snake_case_					,      vector_shuffle=snake_case_					,      prop_tokens_to_load=snake_case_  )					,      *snake_case_					,      **snake_case_					,      )