

import numpy as np
import torch
from torch.utils.data import Dataset

from utils import logger

class        snake_case__    (A__		):







						"""simple docstring"""




						def __init__(       self ,       __lowercase ,       __lowercase  ) ->				int:
									"""simple docstring"""




									a__       :						Tuple							=  params

									a__       :						str							=  np.array(__lowercase  )
									a__       :						List[Any]							=  np.array([len(__lowercase  ) for t in data]  )

									self.check()
									self.remove_long_sequences()
									self.remove_empty_sequences()
									self.remove_unknown_sequences()
									self.check()
									self.print_statistics()

						def __getitem__(       self ,       __lowercase  ) ->				Any:
									"""simple docstring"""




									return (self.token_ids[index], self.lengths[index])

						def __len__(       self  ) ->				Dict:
									"""simple docstring"""




									return len(self.lengths  )

						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				Optional[int]:
									"""simple docstring"""




									assert len(self.token_ids  ) == len(self.lengths  )
									assert all(self.lengths[i] == len(self.token_ids[i]  ) for i in range(len(self.lengths  )  )  )

						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				Tuple:
									"""simple docstring"""




									a__       :						int							=  self.params.max_model_input_size
									a__       :						int							=  self.lengths > max_len
									logger.info(F'''Splitting {sum(__lowercase  )} too long sequences.'''  )

									def divide_chunks(__lowercase ,       __lowercase  ):
												return [l[i : i + n] for i in range(0 ,       len(__lowercase  ) ,       __lowercase  )]

									a__       :						Any							=  []
									a__       :						Optional[int]							=  []
									if self.params.mlm:
												a__       :						Any							=  self.params.special_tok_ids["""cls_token"""], self.params.special_tok_ids["""sep_token"""]
									else:
												a__       :						Dict							=  self.params.special_tok_ids["""bos_token"""], self.params.special_tok_ids["""eos_token"""]

									for seq_, len_ in zip(self.token_ids ,       self.lengths  ):
												assert (seq_[0] == cls_id) and (seq_[-1] == sep_id), seq_
												if len_ <= max_len:
															new_tok_ids.append(seq_  )
															new_lengths.append(len_  )
												else:
															a__       :						int							=  []
															for sub_s in divide_chunks(seq_ ,       max_len - 2  ):
																		if sub_s[0] != cls_id:
																					a__       :						str							=  np.insert(__lowercase ,       0 ,       __lowercase  )
																		if sub_s[-1] != sep_id:
																					a__       :						List[str]							=  np.insert(__lowercase ,       len(__lowercase  ) ,       __lowercase  )
																		assert len(__lowercase  ) <= max_len
																		assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s
																		sub_seqs.append(__lowercase  )

															new_tok_ids.extend(__lowercase  )
															new_lengths.extend([len(__lowercase  ) for l in sub_seqs]  )

									a__       :						Optional[int]							=  np.array(__lowercase  )
									a__       :						Any							=  np.array(__lowercase  )

						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				Optional[Any]:
									"""simple docstring"""




									a__       :						Union[str, Any]							=  len(self  )
									a__       :						List[str]							=  self.lengths > 1_1
									a__       :						Dict							=  self.token_ids[indices]
									a__       :						List[str]							=  self.lengths[indices]
									a__       :						int							=  len(self  )
									logger.info(F'''Remove {init_size - new_size} too short (<=11 tokens) sequences.'''  )

						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				List[Any]:
									"""simple docstring"""




									if "unk_token" not in self.params.special_tok_ids:
												return
									else:
												a__       :						Union[str, Any]							=  self.params.special_tok_ids["""unk_token"""]
									a__       :						List[Any]							=  len(self  )
									a__       :						Optional[int]							=  np.array([np.count_nonzero(a == unk_token_id  ) for a in self.token_ids]  )
									a__       :						Optional[Any]							=  (unk_occs / self.lengths) < 0.5
									a__       :						Tuple							=  self.token_ids[indices]
									a__       :						Union[str, Any]							=  self.lengths[indices]
									a__       :						Tuple							=  len(self  )
									logger.info(F'''Remove {init_size - new_size} sequences with a high level of unknown tokens (50%).'''  )

						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				str:
									"""simple docstring"""




									if not self.params.is_master:
												return
									logger.info(F'''{len(self  )} sequences'''  )
									# data_len = sum(self.lengths)
									# nb_unique_tokens = len(Counter(list(chain(*self.token_ids))))
									# logger.info(f'{data_len} tokens ({nb_unique_tokens} unique)')

									# unk_idx = self.params.special_tok_ids['unk_token']
									# nb_unknown = sum([(t==unk_idx).sum() for t in self.token_ids])
									# logger.info(f'{nb_unknown} unknown tokens (covering {100*nb_unknown/data_len:.2f}% of the data)')

						def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase  ) ->				Optional[int]:
									"""simple docstring"""




									a__       :						Optional[int]							=  [t[0] for t in batch]
									a__       :						Any							=  [t[1] for t in batch]
									assert len(__lowercase  ) == len(__lowercase  )

									# Max for paddings
									a__       :						List[Any]							=  max(__lowercase  )

									# Pad token ids
									if self.params.mlm:
												a__       :						int							=  self.params.special_tok_ids["""pad_token"""]
									else:
												a__       :						List[str]							=  self.params.special_tok_ids["""unk_token"""]
									a__       :						int							=  [list(t.astype(__lowercase  )  ) + [pad_idx] * (max_seq_len_ - len(__lowercase  )) for t in token_ids]
									assert len(tk_  ) == len(__lowercase  )
									assert all(len(__lowercase  ) == max_seq_len_ for t in tk_  )

									a__       :						List[Any]							=  torch.tensor(tk_  )  # (bs, max_seq_len_)
									a__       :						Optional[int]							=  torch.tensor(__lowercase  )  # (bs)
									return tk_t, lg_t









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


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

def      lowerCAmelCase_					(  )							->	Union[str, Any]:







			"""simple docstring"""
			a__       :						List[Any]							=  """https://pypi.org/pypi/diffusers/json"""
			a__       :						Tuple							=  json.loads(request.urlopen(_lowercase).read())["""releases"""].keys()
			return sorted(_lowercase						,       key=lambda _lowercase: version.Version(_lowercase))

def      lowerCAmelCase_					(  )							->	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(_lowercase)
			os.makedirs(_lowercase						,       exist_ok=_lowercase)
			a__       :						Tuple							=  Path(_lowercase) / """__init__.py"""
			if not init_path.exists():
						init_path.touch()

def      lowerCAmelCase_					(  _lowercase    :       Union[str, os.PathLike])							->	Optional[Any]:







			"""simple docstring"""
			init_hf_modules()
			a__       :						Optional[int]							=  Path(_lowercase) / 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(_lowercase						,       exist_ok=_lowercase)
			a__       :						Any							=  dynamic_module_path / """__init__.py"""
			if not init_path.exists():
						init_path.touch()

def      lowerCAmelCase_					(  _lowercase    :       Union[str, Any])							->	Optional[int]:







			"""simple docstring"""
			with open(_lowercase						,       """r"""						,       encoding="""utf-8""") as f:
						a__       :						Union[str, Any]							=  f.read()

			# Imports of the form `import .xxx`
			a__       :						Optional[Any]							=  re.findall("""^\s*import\s+\.(\S+)\s*$"""						,       _lowercase						,       flags=re.MULTILINE)
			# Imports of the form `from .xxx import yyy`
			relative_imports += re.findall("""^\s*from\s+\.(\S+)\s+import"""						,       _lowercase						,       flags=re.MULTILINE)
			# Unique-ify
			return list(set(_lowercase))

def      lowerCAmelCase_					(  _lowercase    :       List[Any])							->	Dict:







			"""simple docstring"""
			a__       :						Dict							=  False
			a__       :						str							=  [module_file]
			a__       :						List[Any]							=  []

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

						a__       :						Dict							=  Path(_lowercase).parent
						a__       :						Any							=  [str(module_path / m) for m in new_imports]
						a__       :						Any							=  [f for f in new_import_files if f not in all_relative_imports]
						a__       :						List[Any]							=  [F'''{f}.py''' for f in new_import_files]

						a__       :						List[Any]							=  len(_lowercase) == 0
						all_relative_imports.extend(_lowercase)

			return all_relative_imports

def      lowerCAmelCase_					(  _lowercase    :       Optional[int])							->	Any:







			"""simple docstring"""
			with open(_lowercase						,       """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*$"""						,       _lowercase						,       flags=re.MULTILINE)
			# Imports of the form `from xxx import yyy`
			imports += re.findall("""^\s*from\s+(\S+)\s+import"""						,       _lowercase						,       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__       :						Optional[Any]							=  list(set(_lowercase))
			a__       :						Union[str, Any]							=  []
			for imp in imports:
						try:
									importlib.import_module(_lowercase)
						except ImportError:
									missing_packages.append(_lowercase)

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

			return get_relative_imports(_lowercase)

def      lowerCAmelCase_					(  _lowercase    :       int						,       _lowercase    :       Tuple)							->	Union[str, Any]:







			"""simple docstring"""
			a__       :						Dict							=  module_path.replace(os.path.sep						,       """.""")
			a__       :						List[Any]							=  importlib.import_module(_lowercase)

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

def      lowerCAmelCase_					(  _lowercase    :       Union[str, Any])							->	Optional[int]:







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

			a__       :						Any							=  dict(inspect.getmembers(_lowercase						,       inspect.isclass))

			a__       :						str							=  None
			for cls_name, cls in cls_members.items():
						if (
						    cls_name != DiffusionPipeline.__name__
						    and issubclass(cls						,       _lowercase)
						    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__       :						str							=  cls

			return pipeline_class

def      lowerCAmelCase_					(  _lowercase    :       Union[str, os.PathLike]						,       _lowercase    :       str						,       _lowercase    :       Optional[Union[str, os.PathLike]] = None						,       _lowercase    :       bool = False						,       _lowercase    :       bool = False						,       _lowercase    :       Optional[Dict[str, str]] = None						,       _lowercase    :       Optional[Union[bool, str]] = None						,       _lowercase    :       Optional[str] = None						,       _lowercase    :       bool = False						,       )							->	Optional[int]:







			"""simple docstring"""
			a__       :						Union[str, Any]							=  str(_lowercase)

			a__       :						Union[str, Any]							=  os.path.join(_lowercase						,       _lowercase)

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

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

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

						a__       :						Any							=  model_info(_lowercase						,       revision=_lowercase						,       token=_lowercase).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[int]							=  submodule_path / commit_hash
						a__       :						Tuple							=  full_submodule + os.path.sep + commit_hash
						create_dynamic_module(_lowercase)

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





def      lowerCAmelCase_					(  _lowercase    :       Union[str, os.PathLike]						,       _lowercase    :       str						,       _lowercase    :       Optional[str] = None						,       _lowercase    :       Optional[Union[str, os.PathLike]] = None						,       _lowercase    :       bool = False						,       _lowercase    :       bool = False						,       _lowercase    :       Optional[Dict[str, str]] = None						,       _lowercase    :       Optional[Union[bool, str]] = None						,       _lowercase    :       Optional[str] = None						,       _lowercase    :       bool = False						,       **_lowercase    :       Union[str, Any]						,       )							->	List[str]:







			"""simple docstring"""
			a__       :						int							=  get_cached_module_file(
			    _lowercase						,       _lowercase						,       cache_dir=_lowercase						,       force_download=_lowercase						,       resume_download=_lowercase						,       proxies=_lowercase						,       use_auth_token=_lowercase						,       revision=_lowercase						,       local_files_only=_lowercase						,       )
			return get_class_in_module(_lowercase						,       final_module.replace(""".py"""						,       """"""))




