






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


__UpperCamelCase   :							Union[str, Any]         =   (
    """https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py"""
)


__UpperCamelCase   :							Optional[Any]         =   logging.get_logger(__name__)  # pylint: disable=invalid-name



def  __UpperCAmelCase						(					)	->      int:

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



def  __UpperCAmelCase						(					)	->      Optional[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(SCREAMING_SNAKE_CASE__     )
   os.makedirs(SCREAMING_SNAKE_CASE__,       exist_ok=SCREAMING_SNAKE_CASE__     )
   __a					  =     Path(SCREAMING_SNAKE_CASE__     ) / '__init__.py'
   if not init_path.exists():
      init_path.touch()



def  __UpperCAmelCase						(					SCREAMING_SNAKE_CASE__:						Union[str, os.PathLike]     )	->      str:

   """simple docstring"""
   init_hf_modules()
   __a					  =     Path(SCREAMING_SNAKE_CASE__     ) / 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(SCREAMING_SNAKE_CASE__,       exist_ok=SCREAMING_SNAKE_CASE__     )
   __a					  =     dynamic_module_path / '__init__.py'
   if not init_path.exists():
      init_path.touch()



def  __UpperCAmelCase						(					SCREAMING_SNAKE_CASE__:						int     )	->      List[Any]:

   """simple docstring"""
   with open(SCREAMING_SNAKE_CASE__,       'r',       encoding='utf-8'     ) as f:
      __a					  =     f.read()

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



def  __UpperCAmelCase						(					SCREAMING_SNAKE_CASE__:						Optional[int]     )	->      Dict:

   """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(SCREAMING_SNAKE_CASE__     )     )

      __a					  =     Path(SCREAMING_SNAKE_CASE__     ).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(SCREAMING_SNAKE_CASE__     ) == 0
      all_relative_imports.extend(SCREAMING_SNAKE_CASE__     )

   return all_relative_imports



def  __UpperCAmelCase						(					SCREAMING_SNAKE_CASE__:						Any     )	->      int:

   """simple docstring"""
   with open(SCREAMING_SNAKE_CASE__,       'r',       encoding='utf-8'     ) as f:
      __a					  =     f.read()

   # Imports of the form `import xxx`
   __a					  =     re.findall('^\s*import\s+(\S+)\s*$',       SCREAMING_SNAKE_CASE__,       flags=re.MULTILINE     )
   # Imports of the form `from xxx import yyy`
   imports += re.findall('^\s*from\s+(\S+)\s+import',       SCREAMING_SNAKE_CASE__,       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(SCREAMING_SNAKE_CASE__     )     )
   __a					  =     []
   for imp in imports:
      try:
         importlib.import_module(SCREAMING_SNAKE_CASE__     )
      except ImportError:
         missing_packages.append(SCREAMING_SNAKE_CASE__     )

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

   return get_relative_imports(SCREAMING_SNAKE_CASE__     )



def  __UpperCAmelCase						(					SCREAMING_SNAKE_CASE__:						List[str],       SCREAMING_SNAKE_CASE__:						Tuple     )	->      Optional[int]:

   """simple docstring"""
   __a					  =     module_path.replace(os.path.sep,       '.'     )
   __a					  =     importlib.import_module(SCREAMING_SNAKE_CASE__     )

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



def  __UpperCAmelCase						(					SCREAMING_SNAKE_CASE__:						Optional[Any]     )	->      Dict:

   """simple docstring"""
   from ..pipelines import DiffusionPipeline

   __a					  =     dict(inspect.getmembers(SCREAMING_SNAKE_CASE__,       inspect.isclass     )     )

   __a					  =     None
   for cls_name, cls in cls_members.items():
      if (
          cls_name != DiffusionPipeline.__name__
          and issubclass(cls,       SCREAMING_SNAKE_CASE__     )
          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  __UpperCAmelCase						(					SCREAMING_SNAKE_CASE__:						Union[str, os.PathLike],       SCREAMING_SNAKE_CASE__:						str,       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,       )	->      List[Any]:

   """simple docstring"""
   __a					  =     str(SCREAMING_SNAKE_CASE__     )

   __a					  =     os.path.join(SCREAMING_SNAKE_CASE__,       SCREAMING_SNAKE_CASE__     )

   if os.path.isfile(SCREAMING_SNAKE_CASE__     ):
      __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=SCREAMING_SNAKE_CASE__,       pipeline=SCREAMING_SNAKE_CASE__     )
      try:
         __a					  =     cached_download(
             SCREAMING_SNAKE_CASE__,       cache_dir=SCREAMING_SNAKE_CASE__,       force_download=SCREAMING_SNAKE_CASE__,       proxies=SCREAMING_SNAKE_CASE__,       resume_download=SCREAMING_SNAKE_CASE__,       local_files_only=SCREAMING_SNAKE_CASE__,       use_auth_token=SCREAMING_SNAKE_CASE__,       )
         __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(
             SCREAMING_SNAKE_CASE__,       SCREAMING_SNAKE_CASE__,       cache_dir=SCREAMING_SNAKE_CASE__,       force_download=SCREAMING_SNAKE_CASE__,       proxies=SCREAMING_SNAKE_CASE__,       resume_download=SCREAMING_SNAKE_CASE__,       local_files_only=SCREAMING_SNAKE_CASE__,       use_auth_token=SCREAMING_SNAKE_CASE__,       )
         __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(SCREAMING_SNAKE_CASE__     )

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

      __a					  =     model_info(SCREAMING_SNAKE_CASE__,       revision=SCREAMING_SNAKE_CASE__,       token=SCREAMING_SNAKE_CASE__     ).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(SCREAMING_SNAKE_CASE__     )

      if not (submodule_path / module_file).exists():
         shutil.copy(SCREAMING_SNAKE_CASE__,       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(
                SCREAMING_SNAKE_CASE__,       f"""{module_needed}.py""",       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__,       )
   return os.path.join(SCREAMING_SNAKE_CASE__,       SCREAMING_SNAKE_CASE__     )



def  __UpperCAmelCase						(					SCREAMING_SNAKE_CASE__:						Union[str, os.PathLike],       SCREAMING_SNAKE_CASE__:						str,       SCREAMING_SNAKE_CASE__:						Optional[str] = None,       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__:						Tuple,       )	->      Union[str, Any]:

   """simple docstring"""
   __a					  =     get_cached_module_file(
       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__,       )
   return get_class_in_module(SCREAMING_SNAKE_CASE__,       final_module.replace('.py',       ''     )     )







'''simple docstring'''



from queue import PriorityQueue
from typing import Any

import numpy as np



def  __UpperCAmelCase						(					SCREAMING_SNAKE_CASE__:						dict,       SCREAMING_SNAKE_CASE__:						str,       SCREAMING_SNAKE_CASE__:						set,       SCREAMING_SNAKE_CASE__:						set,       SCREAMING_SNAKE_CASE__:						dict,       SCREAMING_SNAKE_CASE__:						dict,       SCREAMING_SNAKE_CASE__:						PriorityQueue,       SCREAMING_SNAKE_CASE__:						dict,       SCREAMING_SNAKE_CASE__:						float | int,       )	->      float | int:

   """simple docstring"""
   for nxt, d in graph[v]:
      if nxt in visited_forward:
         continue
      __a					  =     cst_fwd.get(SCREAMING_SNAKE_CASE__,       np.inf     )
      __a					  =     cst_fwd[v] + d
      if new_cost_f < old_cost_f:
         queue.put((new_cost_f, nxt)     )
         __a					  =     new_cost_f
         __a					  =     v
      if nxt in visited_backward:
         if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance:
            __a					  =     cst_fwd[v] + d + cst_bwd[nxt]
   return shortest_distance



def  __UpperCAmelCase						(					SCREAMING_SNAKE_CASE__:						str,       SCREAMING_SNAKE_CASE__:						str,       SCREAMING_SNAKE_CASE__:						dict,       SCREAMING_SNAKE_CASE__:						dict     )	->      int:

   """simple docstring"""
   __a					  =     -1

   __a					  =     set()
   __a					  =     set()
   __a					  =     {source: 0}
   __a					  =     {destination: 0}
   __a					  =     {source: None}
   __a					  =     {destination: None}
   __a					  =     PriorityQueue()
   __a					  =     PriorityQueue()

   __a					  =     np.inf

   queue_forward.put((0, source)     )
   queue_backward.put((0, destination)     )

   if source == destination:
      return 0

   while not queue_forward.empty() and not queue_backward.empty():
      __a  ,      __a					  =     queue_forward.get()
      visited_forward.add(SCREAMING_SNAKE_CASE__     )

      __a  ,      __a					  =     queue_backward.get()
      visited_backward.add(SCREAMING_SNAKE_CASE__     )

      __a					  =     pass_and_relaxation(
          SCREAMING_SNAKE_CASE__,       SCREAMING_SNAKE_CASE__,       SCREAMING_SNAKE_CASE__,       SCREAMING_SNAKE_CASE__,       SCREAMING_SNAKE_CASE__,       SCREAMING_SNAKE_CASE__,       SCREAMING_SNAKE_CASE__,       SCREAMING_SNAKE_CASE__,       SCREAMING_SNAKE_CASE__,       )

      __a					  =     pass_and_relaxation(
          SCREAMING_SNAKE_CASE__,       SCREAMING_SNAKE_CASE__,       SCREAMING_SNAKE_CASE__,       SCREAMING_SNAKE_CASE__,       SCREAMING_SNAKE_CASE__,       SCREAMING_SNAKE_CASE__,       SCREAMING_SNAKE_CASE__,       SCREAMING_SNAKE_CASE__,       SCREAMING_SNAKE_CASE__,       )

      if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance:
         break

   if shortest_distance != np.inf:
      __a					  =     shortest_distance
   return shortest_path_distance


__UpperCamelCase   :							Dict         =   {
    """B""": [["""C""", 1]],
    """C""": [["""D""", 1]],
    """D""": [["""F""", 1]],
    """E""": [["""B""", 1], ["""G""", 2]],
    """F""": [],
    """G""": [["""F""", 1]],
}
__UpperCamelCase   :							int         =   {
    """B""": [["""E""", 1]],
    """C""": [["""B""", 1]],
    """D""": [["""C""", 1]],
    """F""": [["""D""", 1], ["""G""", 1]],
    """E""": [[None, np.inf]],
    """G""": [["""E""", 2]],
}

if __name__ == "__main__":
 import doctest

 doctest.testmod()