


from logging import getLogger
from typing import Any, Callable, List, Optional, Union

import numpy as np
import PIL
import torch

from ...schedulers import DDPMScheduler
from ..onnx_utils import ORT_TO_NP_TYPE, OnnxRuntimeModel
from ..pipeline_utils import ImagePipelineOutput
from . import StableDiffusionUpscalePipeline


UpperCamelCase :				int						    =       getLogger(__name__)


UpperCamelCase :				List[Any]						    =       4
UpperCamelCase :				Optional[Any]						    =       7

UpperCamelCase :				int						    =       {
    '''float16''': torch.floataa,
    '''float32''': torch.floataa,
}
def 							UpperCamelCase_  (				__snake_case			:						int     )->      Dict:




						'''simple docstring'''
						if isinstance(__snake_case	,			torch.Tensor     ):
												return image
						elif isinstance(__snake_case	,			PIL.Image.Image     ):
												__magic_name__ 		=			[image]

						if isinstance(image[0]	,			PIL.Image.Image     ):
												__magic_name__		,			__magic_name__ 		=			image[0].size
												__magic_name__		,			__magic_name__ 		=			(x - x % 64 for x in (w, h))  # resize to integer multiple of 32

												__magic_name__ 		=			[np.array(i.resize((w, h)     )     )[None, :] for i in image]
												__magic_name__ 		=			np.concatenate(__snake_case	,			axis=0     )
												__magic_name__ 		=			np.array(__snake_case     ).astype(np.floataa     ) / 255.0
												__magic_name__ 		=			image.transpose(0	,			3	,			1	,			2     )
												__magic_name__ 		=			2.0 * image - 1.0
												__magic_name__ 		=			torch.from_numpy(__snake_case     )
						elif isinstance(image[0]	,			torch.Tensor     ):
												__magic_name__ 		=			torch.cat(__snake_case	,			dim=0     )

						return image




class     __snake_case							(      _UpperCAmelCase):
					def __init__(	self					:	Any  ,			_lowerCAmelCase					:	OnnxRuntimeModel  ,			_lowerCAmelCase					:	OnnxRuntimeModel  ,			_lowerCAmelCase					:	Any  ,			_lowerCAmelCase					:	OnnxRuntimeModel  ,			_lowerCAmelCase					:	DDPMScheduler  ,			_lowerCAmelCase					:	Any  ,			_lowerCAmelCase					:	int = 3_5_0  ,			)       ->				List[Any]:



											'''simple docstring'''





											super().__init__(
											    vae=_lowerCAmelCase  ,			text_encoder=_lowerCAmelCase  ,			tokenizer=_lowerCAmelCase  ,			unet=_lowerCAmelCase  ,			low_res_scheduler=_lowerCAmelCase  ,			scheduler=_lowerCAmelCase  ,			safety_checker=_lowerCAmelCase  ,			feature_extractor=_lowerCAmelCase  ,			watermarker=_lowerCAmelCase  ,			max_noise_level=_lowerCAmelCase  ,			)
					def __call__(	self					:	int  ,			_lowerCAmelCase					:	Union[str, List[str]]  ,			_lowerCAmelCase					:	Union[torch.FloatTensor, PIL.Image.Image, List[PIL.Image.Image]]  ,			_lowerCAmelCase					:	int = 7_5  ,			_lowerCAmelCase					:	float = 9.0  ,			_lowerCAmelCase					:	int = 2_0  ,			_lowerCAmelCase					:	Optional[Union[str, List[str]]] = None  ,			_lowerCAmelCase					:	Optional[int] = 1  ,			_lowerCAmelCase					:	float = 0.0  ,			_lowerCAmelCase					:	Optional[Union[torch.Generator, List[torch.Generator]]] = None  ,			_lowerCAmelCase					:	Optional[torch.FloatTensor] = None  ,			_lowerCAmelCase					:	Optional[np.ndarray] = None  ,			_lowerCAmelCase					:	Optional[np.ndarray] = None  ,			_lowerCAmelCase					:	Optional[str] = "pil"  ,			_lowerCAmelCase					:	bool = True  ,			_lowerCAmelCase					:	Optional[Callable[[int, int, torch.FloatTensor], None]] = None  ,			_lowerCAmelCase					:	Optional[int] = 1  ,			)       ->				int:



											'''simple docstring'''





											self.check_inputs(_lowerCAmelCase  ,			_lowerCAmelCase  ,			_lowerCAmelCase  ,			_lowerCAmelCase     )

											# 2. Define call parameters
											if prompt is not None and isinstance(_lowerCAmelCase  ,			_lowerCAmelCase     ):
																	__magic_name__ 		=			1
											elif prompt is not None and isinstance(_lowerCAmelCase  ,			_lowerCAmelCase     ):
																	__magic_name__ 		=			len(_lowerCAmelCase     )
											else:
																	__magic_name__ 		=			prompt_embeds.shape[0]

											__magic_name__ 		=			self._execution_device
											# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
											# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
											# corresponds to doing no classifier free guidance.
											__magic_name__ 		=			guidance_scale > 1.0

											# 3. Encode input prompt
											__magic_name__ 		=			self._encode_prompt(
											    _lowerCAmelCase  ,			_lowerCAmelCase  ,			_lowerCAmelCase  ,			_lowerCAmelCase  ,			_lowerCAmelCase  ,			prompt_embeds=_lowerCAmelCase  ,			negative_prompt_embeds=_lowerCAmelCase  ,			)

											__magic_name__ 		=			ORT_TO_PT_TYPE[str(text_embeddings.dtype     )]

											# 4. Preprocess image
											__magic_name__ 		=			preprocess(_lowerCAmelCase     )
											__magic_name__ 		=			image.cpu()

											# 5. set timesteps
											self.scheduler.set_timesteps(_lowerCAmelCase  ,			device=_lowerCAmelCase     )
											__magic_name__ 		=			self.scheduler.timesteps

											# 5. Add noise to image
											__magic_name__ 		=			torch.tensor([noise_level]  ,			dtype=torch.long  ,			device=_lowerCAmelCase     )
											__magic_name__ 		=			torch.randn(image.shape  ,			generator=_lowerCAmelCase  ,			device=_lowerCAmelCase  ,			dtype=_lowerCAmelCase     )
											__magic_name__ 		=			self.low_res_scheduler.add_noise(_lowerCAmelCase  ,			_lowerCAmelCase  ,			_lowerCAmelCase     )

											__magic_name__ 		=			2 if do_classifier_free_guidance else 1
											__magic_name__ 		=			np.concatenate([image] * batch_multiplier * num_images_per_prompt     )
											__magic_name__ 		=			np.concatenate([noise_level] * image.shape[0]     )

											# 6. Prepare latent variables
											__magic_name__		,			__magic_name__ 		=			image.shape[2:]
											__magic_name__ 		=			self.prepare_latents(
											    batch_size * num_images_per_prompt  ,			_lowerCAmelCase  ,			_lowerCAmelCase  ,			_lowerCAmelCase  ,			_lowerCAmelCase  ,			_lowerCAmelCase  ,			_lowerCAmelCase  ,			_lowerCAmelCase  ,			)

											# 7. Check that sizes of image and latents match
											__magic_name__ 		=			image.shape[1]
											if NUM_LATENT_CHANNELS + num_channels_image != NUM_UNET_INPUT_CHANNELS:
																	raise ValueError(
																	    'Incorrect configuration settings! The config of `pipeline.unet` expects'
																	    F''' {NUM_UNET_INPUT_CHANNELS} but received `num_channels_latents`: {NUM_LATENT_CHANNELS} +'''
																	    F''' `num_channels_image`: {num_channels_image} '''
																	    F''' = {NUM_LATENT_CHANNELS+num_channels_image}. Please verify the config of'''
																	    ' `pipeline.unet` or your `image` input.'     )

											# 8. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
											__magic_name__ 		=			self.prepare_extra_step_kwargs(_lowerCAmelCase  ,			_lowerCAmelCase     )

											__magic_name__ 		=			next(
											    (input.type for input in self.unet.model.get_inputs() if input.name == 'timestep')  ,			'tensor(float)'     )
											__magic_name__ 		=			ORT_TO_NP_TYPE[timestep_dtype]

											# 9. Denoising loop
											__magic_name__ 		=			len(_lowerCAmelCase     ) - num_inference_steps * self.scheduler.order
											with self.progress_bar(total=_lowerCAmelCase     ) as progress_bar:
																	for i, t in enumerate(_lowerCAmelCase     ):
																							# expand the latents if we are doing classifier free guidance
																							__magic_name__ 		=			np.concatenate([latents] * 2     ) if do_classifier_free_guidance else latents

																							# concat latents, mask, masked_image_latents in the channel dimension
																							__magic_name__ 		=			self.scheduler.scale_model_input(_lowerCAmelCase  ,			_lowerCAmelCase     )
																							__magic_name__ 		=			np.concatenate([latent_model_input, image]  ,			axis=1     )

																							# timestep to tensor
																							__magic_name__ 		=			np.array([t]  ,			dtype=_lowerCAmelCase     )

																							# predict the noise residual
																							__magic_name__ 		=			self.unet(
																							    sample=_lowerCAmelCase  ,			timestep=_lowerCAmelCase  ,			encoder_hidden_states=_lowerCAmelCase  ,			class_labels=noise_level.astype(np.intaa     )  ,			)[0]

																							# perform guidance
																							if do_classifier_free_guidance:
																													__magic_name__		,			__magic_name__ 		=			np.split(_lowerCAmelCase  ,			2     )
																							__magic_name__ 		=			noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

																							# compute the previous noisy sample x_t -> x_t-1
																							__magic_name__ 		=			self.scheduler.step(
																							    torch.from_numpy(_lowerCAmelCase     )  ,			_lowerCAmelCase  ,			_lowerCAmelCase  ,			**_lowerCAmelCase     ).prev_sample

																							# call the callback, if provided
																							if i == len(_lowerCAmelCase     ) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
																													progress_bar.update()
																													if callback is not None and i % callback_steps == 0:
																																			callback(_lowerCAmelCase  ,			_lowerCAmelCase  ,			_lowerCAmelCase     )

        # 10. Post-processing
											__magic_name__ 		=			self.decode_latents(latents.float()     )

											# 11. Convert to PIL
											if output_type == "pil":
																	__magic_name__ 		=			self.numpy_to_pil(_lowerCAmelCase     )

											if not return_dict:
																	return (image,)

											return ImagePipelineOutput(images=_lowerCAmelCase     )
					def   a (	self					:	Union[str, Any]  ,			_lowerCAmelCase					:	Tuple     )       ->				Dict:



											'''simple docstring'''





											__magic_name__ 		=			1 / 0.0_8333 * latents
											__magic_name__ 		=			self.vae(latent_sample=_lowerCAmelCase     )[0]
											__magic_name__ 		=			np.clip(image / 2 + 0.5  ,			0  ,			1     )
											__magic_name__ 		=			image.transpose((0, 2, 3, 1)     )
											return image







					def   a (	self					:	Tuple  ,			_lowerCAmelCase					:	Union[str, List[str]]  ,			_lowerCAmelCase					:	Dict  ,			_lowerCAmelCase					:	Optional[int]  ,			_lowerCAmelCase					:	bool  ,			_lowerCAmelCase					:	Optional[str]  ,			_lowerCAmelCase					:	Optional[torch.FloatTensor] = None  ,			_lowerCAmelCase					:	Optional[torch.FloatTensor] = None  ,			)       ->				Union[str, Any]:



											'''simple docstring'''





											if prompt is not None and isinstance(_lowerCAmelCase  ,			_lowerCAmelCase     ):
																	__magic_name__ 		=			1
											elif prompt is not None and isinstance(_lowerCAmelCase  ,			_lowerCAmelCase     ):
																	__magic_name__ 		=			len(_lowerCAmelCase     )
											else:
																	__magic_name__ 		=			prompt_embeds.shape[0]

											if prompt_embeds is None:
																	__magic_name__ 		=			self.tokenizer(
																	    _lowerCAmelCase  ,			padding='max_length'  ,			max_length=self.tokenizer.model_max_length  ,			truncation=_lowerCAmelCase  ,			return_tensors='pt'  ,			)
																	__magic_name__ 		=			text_inputs.input_ids
																	__magic_name__ 		=			self.tokenizer(_lowerCAmelCase  ,			padding='longest'  ,			return_tensors='pt'     ).input_ids

																	if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
																	    _lowerCAmelCase  ,			_lowerCAmelCase     ):
																							__magic_name__ 		=			self.tokenizer.batch_decode(
																							    untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]     )
																							logger.warning(
																							    'The following part of your input was truncated because CLIP can only handle sequences up to'
																							    F''' {self.tokenizer.model_max_length} tokens: {removed_text}'''     )

																	# no positional arguments to text_encoder
																	__magic_name__ 		=			self.text_encoder(
																	    input_ids=text_input_ids.int().to(_lowerCAmelCase     )  ,			)
																	__magic_name__ 		=			prompt_embeds[0]

											__magic_name__		,			__magic_name__		,			__magic_name__ 		=			prompt_embeds.shape
											# duplicate text embeddings for each generation per prompt, using mps friendly method
											__magic_name__ 		=			prompt_embeds.repeat(1  ,			_lowerCAmelCase     )
											__magic_name__ 		=			prompt_embeds.reshape(bs_embed * num_images_per_prompt  ,			_lowerCAmelCase  ,			-1     )

											# get unconditional embeddings for classifier free guidance
											if do_classifier_free_guidance and negative_prompt_embeds is None:
																	__magic_name__ 		=			42
																	if negative_prompt is None:
																							__magic_name__ 		=			[''] * batch_size
																	elif type(_lowerCAmelCase     ) is not type(_lowerCAmelCase     ):
																							raise TypeError(
																							    F'''`negative_prompt` should be the same type to `prompt`, but got {type(_lowerCAmelCase     )} !='''
																							    F''' {type(_lowerCAmelCase     )}.'''     )
																	elif isinstance(_lowerCAmelCase  ,			_lowerCAmelCase     ):
																							__magic_name__ 		=			[negative_prompt]
																	elif batch_size != len(_lowerCAmelCase     ):
																							raise ValueError(
																							    F'''`negative_prompt`: {negative_prompt} has batch size {len(_lowerCAmelCase     )}, but `prompt`:'''
																							    F''' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches'''
																							    ' the batch size of `prompt`.'     )
																	else:
																							__magic_name__ 		=			negative_prompt

																	__magic_name__ 		=			text_input_ids.shape[-1]
																	__magic_name__ 		=			self.tokenizer(
																	    _lowerCAmelCase  ,			padding='max_length'  ,			max_length=_lowerCAmelCase  ,			truncation=_lowerCAmelCase  ,			return_tensors='pt'  ,			)

																	# if hasattr(uncond_input, "attention_mask"):
																	#     attention_mask = uncond_input.attention_mask.to(device)
																	# else:
																	#     attention_mask = None

																	__magic_name__ 		=			self.text_encoder(
																	    input_ids=uncond_input.input_ids.int().to(_lowerCAmelCase     )  ,			)
																	__magic_name__ 		=			uncond_embeddings[0]

											if do_classifier_free_guidance:
																	__magic_name__ 		=			uncond_embeddings.shape[1]
																	# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
																	__magic_name__ 		=			uncond_embeddings.repeat(1  ,			_lowerCAmelCase     )
																	__magic_name__ 		=			uncond_embeddings.reshape(batch_size * num_images_per_prompt  ,			_lowerCAmelCase  ,			-1     )

																	# For classifier free guidance, we need to do two forward passes.
																	# Here we concatenate the unconditional and text embeddings into a single batch
																	# to avoid doing two forward passes
																	__magic_name__ 		=			np.concatenate([uncond_embeddings, prompt_embeds]     )

											return prompt_embeds





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

from ...utils import is_tf_available, is_torch_available, logging


UpperCamelCase :				Optional[Any]						    =       logging.get_logger(__name__)

@dataclass
class     __snake_case							:
					SCREAMING_SNAKE_CASE_		:					str
					SCREAMING_SNAKE_CASE_		:					str
					SCREAMING_SNAKE_CASE_		:					Optional[str] 				= None
					SCREAMING_SNAKE_CASE_		:					Optional[str] 				= None
					def   a (	self					:	Tuple     )       ->				Dict:



											'''simple docstring'''





											return json.dumps(dataclasses.asdict(self     )  ,			indent=2     ) + "\n"







@dataclass(frozen=_UpperCAmelCase)
class     __snake_case							:
					SCREAMING_SNAKE_CASE_		:					List[int]
					SCREAMING_SNAKE_CASE_		:					Optional[List[int]] 				= None
					SCREAMING_SNAKE_CASE_		:					Optional[List[int]] 				= None
					SCREAMING_SNAKE_CASE_		:					Optional[Union[int, float]] 				= None
					def   a (	self					:	List[str]     )       ->				str:



											'''simple docstring'''





											return json.dumps(dataclasses.asdict(self     )     ) + "\n"







class     __snake_case							:
					def   a (	self					:	Union[str, Any]  ,			_lowerCAmelCase					:	List[str]     )       ->				List[Any]:



											'''simple docstring'''





											raise NotImplementedError()
					def   a (	self					:	Optional[Any]  ,			_lowerCAmelCase					:	str     )       ->				List[Any]:



											'''simple docstring'''





											raise NotImplementedError()
					def   a (	self					:	List[str]  ,			_lowerCAmelCase					:	Optional[Any]     )       ->				Optional[Any]:



											'''simple docstring'''





											raise NotImplementedError()
					def   a (	self					:	Optional[int]  ,			_lowerCAmelCase					:	Union[str, Any]     )       ->				int:



											'''simple docstring'''





											raise NotImplementedError()
					def   a (	self					:	Any     )       ->				int:



											'''simple docstring'''





											raise NotImplementedError()
					def   a (	self					:	int  ,			_lowerCAmelCase					:	Optional[int]     )       ->				Dict:



											'''simple docstring'''





											if len(self.get_labels()     ) > 1:
																	__magic_name__ 		=			self.get_labels()[int(example.label     )]
											return example







					@classmethod
					def   a (	cls					:	Dict  ,			_lowerCAmelCase					:	int  ,			_lowerCAmelCase					:	Optional[Any]=None     )       ->				int:



											'''simple docstring'''





											with open(_lowerCAmelCase  ,			'r'  ,			encoding='utf-8-sig'     ) as f:
																	return list(csv.reader(_lowerCAmelCase  ,			delimiter='\t'  ,			quotechar=_lowerCAmelCase     )     )







class     __snake_case							(      _UpperCAmelCase):
					def __init__(	self					:	List[Any]  ,			_lowerCAmelCase					:	str=None  ,			_lowerCAmelCase					:	Dict=None  ,			_lowerCAmelCase					:	List[Any]="classification"  ,			_lowerCAmelCase					:	List[Any]=False     )       ->				Any:



											'''simple docstring'''





											__magic_name__ 		=			[] if labels is None else labels
											__magic_name__ 		=			[] if examples is None else examples
											__magic_name__ 		=			mode
											__magic_name__ 		=			verbose
					def __len__(	self					:	Any     )       ->				Union[str, Any]:



											'''simple docstring'''





											return len(self.examples     )
					def __getitem__(	self					:	Tuple  ,			_lowerCAmelCase					:	Dict     )       ->				Any:



											'''simple docstring'''





											if isinstance(_lowerCAmelCase  ,			_lowerCAmelCase     ):
																	return SingleSentenceClassificationProcessor(labels=self.labels  ,			examples=self.examples[idx]     )
											return self.examples[idx]
					@classmethod
					def   a (	cls					:	List[Any]  ,			_lowerCAmelCase					:	Tuple  ,			_lowerCAmelCase					:	Union[str, Any]=""  ,			_lowerCAmelCase					:	Optional[Any]=0  ,			_lowerCAmelCase					:	Optional[int]=1  ,			_lowerCAmelCase					:	List[str]=None  ,			_lowerCAmelCase					:	str=False  ,			**_lowerCAmelCase					:	Dict     )       ->				Union[str, Any]:



											'''simple docstring'''





											__magic_name__ 		=			cls(**_lowerCAmelCase     )
											processor.add_examples_from_csv(
											    _lowerCAmelCase  ,			split_name=_lowerCAmelCase  ,			column_label=_lowerCAmelCase  ,			column_text=_lowerCAmelCase  ,			column_id=_lowerCAmelCase  ,			skip_first_row=_lowerCAmelCase  ,			overwrite_labels=_lowerCAmelCase  ,			overwrite_examples=_lowerCAmelCase  ,			)
											return processor
					@classmethod
					def   a (	cls					:	Optional[Any]  ,			_lowerCAmelCase					:	List[Any]  ,			_lowerCAmelCase					:	Optional[Any]=None  ,			**_lowerCAmelCase					:	Union[str, Any]     )       ->				Tuple:



											'''simple docstring'''





											__magic_name__ 		=			cls(**_lowerCAmelCase     )
											processor.add_examples(_lowerCAmelCase  ,			labels=_lowerCAmelCase     )
											return processor
					def   a (	self					:	Union[str, Any]  ,			_lowerCAmelCase					:	str  ,			_lowerCAmelCase					:	Optional[Any]=""  ,			_lowerCAmelCase					:	Optional[Any]=0  ,			_lowerCAmelCase					:	str=1  ,			_lowerCAmelCase					:	Any=None  ,			_lowerCAmelCase					:	List[str]=False  ,			_lowerCAmelCase					:	Dict=False  ,			_lowerCAmelCase					:	Any=False  ,			)       ->				Tuple:



											'''simple docstring'''





											__magic_name__ 		=			self._read_tsv(_lowerCAmelCase     )
											if skip_first_row:
																	__magic_name__ 		=			lines[1:]
											__magic_name__ 		=			[]
											__magic_name__ 		=			[]
											__magic_name__ 		=			[]
											for i, line in enumerate(_lowerCAmelCase     ):
																	texts.append(line[column_text]     )
																	labels.append(line[column_label]     )
																	if column_id is not None:
																							ids.append(line[column_id]     )
																	else:
																							__magic_name__ 		=			F'''{split_name}-{i}''' if split_name else str(_lowerCAmelCase     )
																							ids.append(_lowerCAmelCase     )

											return self.add_examples(
											    _lowerCAmelCase  ,			_lowerCAmelCase  ,			_lowerCAmelCase  ,			overwrite_labels=_lowerCAmelCase  ,			overwrite_examples=_lowerCAmelCase     )
					def   a (	self					:	Any  ,			_lowerCAmelCase					:	Optional[int]  ,			_lowerCAmelCase					:	Optional[Any]=None  ,			_lowerCAmelCase					:	Any=None  ,			_lowerCAmelCase					:	Optional[int]=False  ,			_lowerCAmelCase					:	List[str]=False     )       ->				Dict:



											'''simple docstring'''





											if labels is not None and len(_lowerCAmelCase     ) != len(_lowerCAmelCase     ):
																	raise ValueError(
																	    F'''Text and labels have mismatched lengths {len(_lowerCAmelCase     )} and {len(_lowerCAmelCase     )}'''     )
											if ids is not None and len(_lowerCAmelCase     ) != len(_lowerCAmelCase     ):
																	raise ValueError(F'''Text and ids have mismatched lengths {len(_lowerCAmelCase     )} and {len(_lowerCAmelCase     )}'''     )
											if ids is None:
																	__magic_name__ 		=			[None] * len(_lowerCAmelCase     )
											if labels is None:
																	__magic_name__ 		=			[None] * len(_lowerCAmelCase     )
											__magic_name__ 		=			[]
											__magic_name__ 		=			set()
											for text_or_text_and_label, label, guid in zip(_lowerCAmelCase  ,			_lowerCAmelCase  ,			_lowerCAmelCase     ):
																	if isinstance(_lowerCAmelCase  ,			(tuple, list)     ) and label is None:
																							__magic_name__		,			__magic_name__ 		=			text_or_text_and_label
																	else:
																							__magic_name__ 		=			text_or_text_and_label
																	added_labels.add(_lowerCAmelCase     )
																	examples.append(InputExample(guid=_lowerCAmelCase  ,			text_a=_lowerCAmelCase  ,			text_b=_lowerCAmelCase  ,			label=_lowerCAmelCase     )     )

											# Update examples
											if overwrite_examples:
																	__magic_name__ 		=			examples
											else:
																	self.examples.extend(_lowerCAmelCase     )

											# Update labels
											if overwrite_labels:
																	__magic_name__ 		=			list(_lowerCAmelCase     )
											else:
																	__magic_name__ 		=			list(set(self.labels     ).union(_lowerCAmelCase     )     )

											return self.examples







					def   a (	self					:	Optional[int]  ,			_lowerCAmelCase					:	Tuple  ,			_lowerCAmelCase					:	Optional[int]=None  ,			_lowerCAmelCase					:	Dict=False  ,			_lowerCAmelCase					:	Tuple=0  ,			_lowerCAmelCase					:	List[str]=True  ,			_lowerCAmelCase					:	List[str]=None  ,			)       ->				Dict:



											'''simple docstring'''





											if max_length is None:
																	__magic_name__ 		=			tokenizer.max_len

											__magic_name__ 		=			{label: i for i, label in enumerate(self.labels     )}

											__magic_name__ 		=			[]
											for ex_index, example in enumerate(self.examples     ):
																	if ex_index % 1_0_0_0_0 == 0:
																							logger.info(F'''Tokenizing example {ex_index}'''     )

																	__magic_name__ 		=			tokenizer.encode(
																	    example.text_a  ,			add_special_tokens=_lowerCAmelCase  ,			max_length=min(_lowerCAmelCase  ,			tokenizer.max_len     )  ,			)
																	all_input_ids.append(_lowerCAmelCase     )

											__magic_name__ 		=			max(len(_lowerCAmelCase     ) for input_ids in all_input_ids     )

											__magic_name__ 		=			[]
											for ex_index, (input_ids, example) in enumerate(zip(_lowerCAmelCase  ,			self.examples     )     ):
																	if ex_index % 1_0_0_0_0 == 0:
																							logger.info(F'''Writing example {ex_index}/{len(self.examples     )}'''     )
																	# The mask has 1 for real tokens and 0 for padding tokens. Only real
																	# tokens are attended to.
																	__magic_name__ 		=			[1 if mask_padding_with_zero else 0] * len(_lowerCAmelCase     )

																	# Zero-pad up to the sequence length.
																	__magic_name__ 		=			batch_length - len(_lowerCAmelCase     )
																	if pad_on_left:
																							__magic_name__ 		=			([pad_token] * padding_length) + input_ids
																							__magic_name__ 		=			([0 if mask_padding_with_zero else 1] * padding_length) + attention_mask
																	else:
																							__magic_name__ 		=			input_ids + ([pad_token] * padding_length)
																							__magic_name__ 		=			attention_mask + ([0 if mask_padding_with_zero else 1] * padding_length)

																	if len(_lowerCAmelCase     ) != batch_length:
																							raise ValueError(F'''Error with input length {len(_lowerCAmelCase     )} vs {batch_length}'''     )
																	if len(_lowerCAmelCase     ) != batch_length:
																							raise ValueError(F'''Error with input length {len(_lowerCAmelCase     )} vs {batch_length}'''     )

																	if self.mode == "classification":
																							__magic_name__ 		=			label_map[example.label]
																	elif self.mode == "regression":
																							__magic_name__ 		=			float(example.label     )
																	else:
																							raise ValueError(self.mode     )

																	if ex_index < 5 and self.verbose:
																							logger.info('*** Example ***'     )
																							logger.info(F'''guid: {example.guid}'''     )
																							logger.info(F'''input_ids: {" ".join([str(_lowerCAmelCase     ) for x in input_ids]     )}'''     )
																							logger.info(F'''attention_mask: {" ".join([str(_lowerCAmelCase     ) for x in attention_mask]     )}'''     )
																							logger.info(F'''label: {example.label} (id = {label})'''     )

																	features.append(InputFeatures(input_ids=_lowerCAmelCase  ,			attention_mask=_lowerCAmelCase  ,			label=_lowerCAmelCase     )     )

											if return_tensors is None:
																	return features
											elif return_tensors == "tf":
																	if not is_tf_available():
																							raise RuntimeError('return_tensors set to \'tf\' but TensorFlow 2.0 can\'t be imported'     )
																	import tensorflow as tf

																	def gen():
																							for ex in features:
																													yield ({"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label)

																	__magic_name__ 		=			tf.data.Dataset.from_generator(
																	    _lowerCAmelCase  ,			({'input_ids': tf.intaa, 'attention_mask': tf.intaa}, tf.intaa)  ,			({'input_ids': tf.TensorShape([None]     ), 'attention_mask': tf.TensorShape([None]     )}, tf.TensorShape([]     ))  ,			)
																	return dataset
											elif return_tensors == "pt":
																	if not is_torch_available():
																							raise RuntimeError('return_tensors set to \'pt\' but PyTorch can\'t be imported'     )
																	import torch
																	from torch.utils.data import TensorDataset

																	__magic_name__ 		=			torch.tensor([f.input_ids for f in features]  ,			dtype=torch.long     )
																	__magic_name__ 		=			torch.tensor([f.attention_mask for f in features]  ,			dtype=torch.long     )
																	if self.mode == "classification":
																							__magic_name__ 		=			torch.tensor([f.label for f in features]  ,			dtype=torch.long     )
																	elif self.mode == "regression":
																							__magic_name__ 		=			torch.tensor([f.label for f in features]  ,			dtype=torch.float     )

																	__magic_name__ 		=			TensorDataset(_lowerCAmelCase  ,			_lowerCAmelCase  ,			_lowerCAmelCase     )
																	return dataset
											else:
																	raise ValueError('return_tensors should be one of \'tf\' or \'pt\''     )

