

'''simple docstring'''




def 						UpperCamelCase	(			a		,						a			)				->     list:






					'''simple docstring'''
					__magic_name__						       =    word.split()

					def justify(a		,						a		,						a			) -> str:
										__magic_name__						       =    max_width - width
										__magic_name__						       =    len(UpperCAmelCase_			)
										if len(UpperCAmelCase_			) == 1:
															# if there is only word in line
															# just insert overall_spaces_count for the remainder of line
															return line[0] + " " * overall_spaces_count
										else:
															__magic_name__						       =    words_count - 1
															# num_spaces_between_words_list[i] : tells you to insert
															# num_spaces_between_words_list[i] spaces
															# after word on line[i]
															__magic_name__						       =    spaces_to_insert_between_words * [
															    overall_spaces_count // spaces_to_insert_between_words
															]
															__magic_name__						       =    (
															    overall_spaces_count % spaces_to_insert_between_words
															)
															# distribute spaces via round robin to the left words
															for i in range(UpperCAmelCase_			):
																				num_spaces_between_words_list[i] += 1
															__magic_name__						       =    []
															for i in range(UpperCAmelCase_			):
																				# add the word
																				aligned_words_list.append(line[i]			)
																				# add the spaces to insert
																				aligned_words_list.append(num_spaces_between_words_list[i] * ''' '''			)
															# just add the last word to the sentence
															aligned_words_list.append(line[-1]			)
															# join the aligned words list to form a justified line
															return "".join(UpperCAmelCase_			)

					__magic_name__						       =    []
					__magic_name__						       =    []
					__magic_name__						       =    0
					for word in words:
										if width + len(UpperCAmelCase_			) + len(UpperCAmelCase_			) <= max_width:
															# keep adding words until we can fill out max_width
															# width = sum of length of all words (without overall_spaces_count)
															# len(word) = length of current word
															# len(line) = number of overall_spaces_count to insert between words
															line.append(UpperCAmelCase_			)
															width += len(UpperCAmelCase_			)
										else:
															# justify the line and add it to result
															answer.append(justify(UpperCAmelCase_		,						UpperCAmelCase_		,						UpperCAmelCase_			)			)
															# reset new line and new width
															__magic_name__						       =    [word], len(UpperCAmelCase_			)
					__magic_name__						       =    max_width - width - len(UpperCAmelCase_			)
					answer.append(''' '''.join(UpperCAmelCase_			) + (remaining_spaces + 1) * ''' '''			)
					return answer


if __name__ == "__main__":
						from doctest import testmod

						testmod()









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






