


'''simple docstring'''







from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
from PIL import Image

from ...utils import (
    BaseOutput,
    OptionalDependencyNotAvailable,
    is_flax_available,
    is_k_diffusion_available,
    is_k_diffusion_version,
    is_onnx_available,
    is_torch_available,
    is_transformers_available,
    is_transformers_version,
)







@dataclass
class A__       (						__lowercase      ):
      __UpperCamelCase       :  Union[List[PIL.Image.Image], np.ndarray]
      __UpperCamelCase       :  Optional[List[bool]]


try:
   if not (is_transformers_available() and is_torch_available()):
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   from ...utils.dummy_torch_and_transformers_objects import *  # noqa F403
else:
   from .pipeline_cycle_diffusion import CycleDiffusionPipeline
   from .pipeline_stable_diffusion import StableDiffusionPipeline
   from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline
   from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline
   from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline
   from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy
   from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline
   from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline
   from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline
   from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline
   from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline
   from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline
   from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline
   from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline
   from .pipeline_stable_unclip import StableUnCLIPPipeline
   from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline
   from .safety_checker import StableDiffusionSafetyChecker
   from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer

try:
   if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.25.0''')):
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline
else:
   from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline


try:
   if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.26.0''')):
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   from ...utils.dummy_torch_and_transformers_objects import (
       StableDiffusionDepthaImgPipeline,
       StableDiffusionDiffEditPipeline,
       StableDiffusionPixaPixZeroPipeline,
   )
else:
   from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline
   from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline
   from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline


try:
   if not (
       is_torch_available()
       and is_transformers_available()
       and is_k_diffusion_available()
       and is_k_diffusion_version('''>=''', '''0.0.12''')
   ):
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import *  # noqa F403
else:
   from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline

try:
   if not (is_transformers_available() and is_onnx_available()):
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   from ...utils.dummy_onnx_objects import *  # noqa F403
else:
   from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline
   from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline
   from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline
   from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy
   from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline

if is_transformers_available() and is_flax_available():
   import flax







   @flax.struct.dataclass
   class A__       (						__lowercase      ):
         __UpperCamelCase       :  np.ndarray
         __UpperCamelCase       :  List[bool]

   from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState
   from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline
   from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline
   from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline
   from .safety_checker_flax import FlaxStableDiffusionSafetyChecker





import os
import time
import warnings
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import logging
from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors
from ..processors.utils import InputFeatures


a__				=		logging.get_logger(__name__)

@dataclass
class 				UpperCAmelCase_		:
							"""simple docstring"""







							UpperCAmelCase__       :						str	    =    field(metadata={"help": "The name of the task to train on: " + ", ".join(glue_processors.keys()   )}   )
							UpperCAmelCase__       :						str	    =    field(
							    metadata={"help": "The input data dir. Should contain the .tsv files (or other data files) for the task."}   )
							UpperCAmelCase__       :						int	    =    field(
							    default=128				,       metadata={
							        "help": (
							            "The maximum total input sequence length after tokenization. Sequences longer "
							            "than this will be truncated, sequences shorter will be padded."
							        )
							    }				,       )
							UpperCAmelCase__       :						bool	    =    field(
							    default=__lowercase				,       metadata={"help": "Overwrite the cached training and evaluation sets"}   )


							def 				__lowercase				(			self       )    ->    List[Any]:
												_a	:    List[Any]         =		self.task_name.lower()



class 				UpperCAmelCase_		(			__lowercase   ):
							"""simple docstring"""







							UpperCAmelCase__       :						List[str]	    =    "train"
							UpperCAmelCase__       :						List[str]	    =    "dev"
							UpperCAmelCase__       :						Union[str, Any]	    =    "test"



class 				UpperCAmelCase_		(			__lowercase   ):
							"""simple docstring"""







							UpperCAmelCase__       :						GlueDataTrainingArguments
							UpperCAmelCase__       :						str
							UpperCAmelCase__       :						List[InputFeatures]


							def __init__(			self       ,							_a       ,							_a       ,							_a = None       ,							_a = Split.train       ,							_a = None       ,							)    ->    str:
												warnings.warn(
												    '''This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets '''
												    '''library. You can have a look at this example script for pointers: '''
												    '''https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py'''       ,							_a       ,							)
												_a	:    List[str]         =		args
												_a	:    List[str]         =		glue_processors[args.task_name]()
												_a	:    List[Any]         =		glue_output_modes[args.task_name]
												if isinstance(_a       ,							_a       ):
																	try:
																						_a	:    Any         =		Split[mode]
																	except KeyError:
																						raise KeyError('''mode is not a valid split name'''       )
        # Load data features from cache or dataset file
												_a	:    Union[str, Any]         =		os.path.join(
												    cache_dir if cache_dir is not None else args.data_dir       ,							F"""cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}"""       ,							)
												_a	:    str         =		self.processor.get_labels()
												if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in (
												    "RobertaTokenizer",
												    "RobertaTokenizerFast",
												    "XLMRobertaTokenizer",
												    "BartTokenizer",
												    "BartTokenizerFast",
												):
																	# HACK(label indices are swapped in RoBERTa pretrained model)
																	_a      ,					_a	:    Optional[int]         =		label_list[2], label_list[1]
												_a	:    Dict         =		label_list

												# Make sure only the first process in distributed training processes the dataset,
												# and the others will use the cache.
												_a	:    Optional[int]         =		cached_features_file + '''.lock'''
												with FileLock(_a       ):
																	if os.path.exists(_a       ) and not args.overwrite_cache:
																						_a	:    List[Any]         =		time.time()
																						_a	:    str         =		torch.load(_a       )
																						logger.info(
																						    F"""Loading features from cached file {cached_features_file} [took %.3f s]"""       ,							time.time() - start       )
																	else:
																						logger.info(F"""Creating features from dataset file at {args.data_dir}"""       )

																						if mode == Split.dev:
																											_a	:    str         =		self.processor.get_dev_examples(args.data_dir       )
																						elif mode == Split.test:
																											_a	:    Any         =		self.processor.get_test_examples(args.data_dir       )
																						else:
																											_a	:    List[str]         =		self.processor.get_train_examples(args.data_dir       )
																						if limit_length is not None:
																											_a	:    Dict         =		examples[:limit_length]
																						_a	:    Union[str, Any]         =		glue_convert_examples_to_features(
																						    _a       ,							_a       ,							max_length=args.max_seq_length       ,							label_list=_a       ,							output_mode=self.output_mode       ,							)
																						_a	:    Optional[int]         =		time.time()
																						torch.save(self.features       ,							_a       )
																						# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
																						logger.info(
																						    F"""Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]"""       )


							def __len__(			self       )    ->    Optional[int]:
												return len(self.features       )


							def __getitem__(			self       ,							_a       )    ->    InputFeatures:
												return self.features[i]




							def 				__lowercase				(			self       )    ->    Tuple:
												return self.label_list



