


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




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





def lowerCamelCase__     (		):







   '''simple docstring'''




   if HF_MODULES_CACHE in sys.path:
      return

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





def lowerCamelCase__     (		__lowerCamelCase			:				Union[str, os.PathLike]				):







   '''simple docstring'''




   init_hf_modules()
   _UpperCAmelCase  :  Optional[int]				       =Path(__lowerCamelCase				) / 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(__lowerCamelCase			,       exist_ok=__lowerCamelCase				)
   _UpperCAmelCase  :  Any				       =dynamic_module_path / '__init__.py'
   if not init_path.exists():
      init_path.touch()





def lowerCamelCase__     (		__lowerCamelCase			:				List[Any]				):







   '''simple docstring'''




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

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





def lowerCamelCase__     (		__lowerCamelCase			:				Any				):







   '''simple docstring'''




   _UpperCAmelCase  :  int				       =False
   _UpperCAmelCase  :  Tuple				       =[module_file]
   _UpperCAmelCase  :  Dict				       =[]

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

      _UpperCAmelCase  :  Optional[Any]				       =Path(__lowerCamelCase				).parent
      _UpperCAmelCase  :  str				       =[str(module_path / m				) for m in new_imports]
      _UpperCAmelCase  :  Union[str, Any]				       =[f for f in new_import_files if f not in all_relative_imports]
      _UpperCAmelCase  :  List[Any]				       =[f"{f}.py" for f in new_import_files]

      _UpperCAmelCase  :  Union[str, Any]				       =len(__lowerCamelCase				) == 0
      all_relative_imports.extend(__lowerCamelCase				)

   return all_relative_imports





def lowerCamelCase__     (		__lowerCamelCase			:				List[Any]				):







   '''simple docstring'''




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

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

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

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

   return get_relative_imports(__lowerCamelCase				)





def lowerCamelCase__     (		__lowerCamelCase			:				Optional[int]			,       __lowerCamelCase			:				Optional[Any]				):







   '''simple docstring'''




   _UpperCAmelCase  :  str				       =module_path.replace(os.path.sep			,       '.'				)
   _UpperCAmelCase  :  List[str]				       =importlib.import_module(__lowerCamelCase				)

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





def lowerCamelCase__     (		__lowerCamelCase			:				Tuple				):







   '''simple docstring'''




   from ..pipelines import DiffusionPipeline

   _UpperCAmelCase  :  Any				       =dict(inspect.getmembers(__lowerCamelCase			,       inspect.isclass				)				)

   _UpperCAmelCase  :  Optional[int]				       =None
   for cls_name, cls in cls_members.items():
      if (
          cls_name != DiffusionPipeline.__name__
          and issubclass(cls			,       __lowerCamelCase				)
          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}."				)
         _UpperCAmelCase  :  List[Any]				       =cls

   return pipeline_class





def lowerCamelCase__     (		__lowerCamelCase			:				Union[str, os.PathLike]			,       __lowerCamelCase			:				str			,       __lowerCamelCase			:				Optional[Union[str, os.PathLike]] = None			,       __lowerCamelCase			:				bool = False			,       __lowerCamelCase			:				bool = False			,       __lowerCamelCase			:				Optional[Dict[str, str]] = None			,       __lowerCamelCase			:				Optional[Union[bool, str]] = None			,       __lowerCamelCase			:				Optional[str] = None			,       __lowerCamelCase			:				bool = False			,       ):







   '''simple docstring'''




   _UpperCAmelCase  :  int				       =str(__lowerCamelCase				)

   _UpperCAmelCase  :  Any				       =os.path.join(__lowerCamelCase			,       __lowerCamelCase				)

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

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

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

      _UpperCAmelCase  :  Union[str, Any]				       =model_info(__lowerCamelCase			,       revision=__lowerCamelCase			,       token=__lowerCamelCase				).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.
      _UpperCAmelCase  :  Optional[Any]				       =submodule_path / commit_hash
      _UpperCAmelCase  :  Optional[int]				       =full_submodule + os.path.sep + commit_hash
      create_dynamic_module(__lowerCamelCase				)

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





def lowerCamelCase__     (		__lowerCamelCase			:				Union[str, os.PathLike]			,       __lowerCamelCase			:				str			,       __lowerCamelCase			:				Optional[str] = None			,       __lowerCamelCase			:				Optional[Union[str, os.PathLike]] = None			,       __lowerCamelCase			:				bool = False			,       __lowerCamelCase			:				bool = False			,       __lowerCamelCase			:				Optional[Dict[str, str]] = None			,       __lowerCamelCase			:				Optional[Union[bool, str]] = None			,       __lowerCamelCase			:				Optional[str] = None			,       __lowerCamelCase			:				bool = False			,       **__lowerCamelCase			:				Tuple			,       ):







   '''simple docstring'''




   _UpperCAmelCase  :  List[Any]				       =get_cached_module_file(
       __lowerCamelCase			,       __lowerCamelCase			,       cache_dir=__lowerCamelCase			,       force_download=__lowerCamelCase			,       resume_download=__lowerCamelCase			,       proxies=__lowerCamelCase			,       use_auth_token=__lowerCamelCase			,       revision=__lowerCamelCase			,       local_files_only=__lowerCamelCase			,       )
   return get_class_in_module(__lowerCamelCase			,       final_module.replace('.py'			,       ''				)				)





'''simple docstring'''






import math
import time
from typing import Dict, List, Optional

from torch.utils.data import Dataset

from transformers import SeqaSeqTrainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


if is_torch_tpu_available(check_device=False):
 import torch_xla.core.xla_model as xm
 import torch_xla.debug.metrics as met






class    __magic_name__				(						lowerCAmelCase							):






       def __init__(     self    ,				*snake_case    ,				snake_case=None    ,				snake_case=None    ,				**snake_case)		->    Tuple:




          '''simple docstring'''
          super().__init__(*snake_case    ,				**snake_case)
          _UpperCAmelCase  :  Any				       =eval_examples
          _UpperCAmelCase  :  Optional[int]				       =post_process_function






       def      lowerCAmelCase						(     self    ,				snake_case = None    ,				snake_case=None    ,				snake_case = None    ,				snake_case = "eval"    ,				**snake_case    ,				)		->    Dict[str, float]:




          '''simple docstring'''
          _UpperCAmelCase  :  Tuple				       =gen_kwargs.copy()
          _UpperCAmelCase  :  int				       =(
              gen_kwargs['max_length'] if gen_kwargs.get('max_length') is not None else self.args.generation_max_length
          )
          _UpperCAmelCase  :  Dict				       =(
              gen_kwargs['num_beams'] if gen_kwargs.get('num_beams') is not None else self.args.generation_num_beams
          )
          _UpperCAmelCase  :  Dict				       =gen_kwargs

          _UpperCAmelCase  :  Tuple				       =self.eval_dataset if eval_dataset is None else eval_dataset
          _UpperCAmelCase  :  Union[str, Any]				       =self.get_eval_dataloader(snake_case)
          _UpperCAmelCase  :  Tuple				       =self.eval_examples if eval_examples is None else eval_examples

          # Temporarily disable metric computation, we will do it in the loop here.
          _UpperCAmelCase  :  Dict				       =self.compute_metrics
          _UpperCAmelCase  :  Optional[Any]				       =None
          _UpperCAmelCase  :  str				       =time.time()
          _UpperCAmelCase  :  int				       =self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
          try:
             _UpperCAmelCase  :  str				       =eval_loop(
                 snake_case    ,				description='Evaluation'    ,				prediction_loss_only=True if compute_metrics is None else None    ,				ignore_keys=snake_case    ,				metric_key_prefix=snake_case    ,				)
          finally:
             _UpperCAmelCase  :  str				       =compute_metrics
          _UpperCAmelCase  :  Optional[int]				       =self.args.eval_batch_size * self.args.world_size
          if f"{metric_key_prefix}_jit_compilation_time" in output.metrics:
             start_time += output.metrics[f"{metric_key_prefix}_jit_compilation_time"]
          output.metrics.update(
              speed_metrics(
                  snake_case    ,				snake_case    ,				num_samples=output.num_samples    ,				num_steps=math.ceil(output.num_samples / total_batch_size)    ,				))

          if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
             # Only the main node write the results by default
             _UpperCAmelCase  :  Tuple				       =self.post_process_function(snake_case    ,				snake_case    ,				snake_case)
             _UpperCAmelCase  :  Union[str, Any]				       =self.compute_metrics(snake_case)

             # Prefix all keys with metric_key_prefix + '_'
             for key in list(metrics.keys()):
                if not key.startswith(f"{metric_key_prefix}_"):
                   _UpperCAmelCase  :  Any				       =metrics.pop(snake_case)

             metrics.update(output.metrics)
          else:
             _UpperCAmelCase  :  str				       =output.metrics

          if self.args.should_log:
             # Only the main node log the results by default
             self.log(snake_case)

          if self.args.tpu_metrics_debug or self.args.debug:
             # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
             xm.master_print(met.metrics_report())

          _UpperCAmelCase  :  Any				       =self.callback_handler.on_evaluate(self.args    ,				self.state    ,				self.control    ,				snake_case)
          return metrics






       def      lowerCAmelCase						(     self    ,				snake_case    ,				snake_case    ,				snake_case=None    ,				snake_case = "test"    ,				**snake_case)		->    Dict:




          '''simple docstring'''
          _UpperCAmelCase  :  Optional[int]				       =gen_kwargs.copy()

          _UpperCAmelCase  :  int				       =self.get_test_dataloader(snake_case)

          # Temporarily disable metric computation, we will do it in the loop here.
          _UpperCAmelCase  :  str				       =self.compute_metrics
          _UpperCAmelCase  :  Union[str, Any]				       =None
          _UpperCAmelCase  :  Union[str, Any]				       =time.time()
          _UpperCAmelCase  :  Tuple				       =self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
          try:
             _UpperCAmelCase  :  Any				       =eval_loop(
                 snake_case    ,				description='Prediction'    ,				prediction_loss_only=True if compute_metrics is None else None    ,				ignore_keys=snake_case    ,				metric_key_prefix=snake_case    ,				)
          finally:
             _UpperCAmelCase  :  Any				       =compute_metrics

          _UpperCAmelCase  :  Dict				       =self.args.eval_batch_size * self.args.world_size
          if f"{metric_key_prefix}_jit_compilation_time" in output.metrics:
             start_time += output.metrics[f"{metric_key_prefix}_jit_compilation_time"]
          output.metrics.update(
              speed_metrics(
                  snake_case    ,				snake_case    ,				num_samples=output.num_samples    ,				num_steps=math.ceil(output.num_samples / total_batch_size)    ,				))
          if self.post_process_function is None or self.compute_metrics is None:
             return output

          _UpperCAmelCase  :  Tuple				       =self.post_process_function(snake_case    ,				snake_case    ,				snake_case    ,				'predict')
          _UpperCAmelCase  :  Union[str, Any]				       =self.compute_metrics(snake_case)

          # Prefix all keys with metric_key_prefix + '_'
          for key in list(metrics.keys()):
             if not key.startswith(f"{metric_key_prefix}_"):
                _UpperCAmelCase  :  Any				       =metrics.pop(snake_case)
          metrics.update(output.metrics)
          return PredictionOutput(predictions=predictions.predictions    ,				label_ids=predictions.label_ids    ,				metrics=snake_case)

