






'''simple docstring'''




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


lowerCAmelCase__          =						logging.get_logger(__name__)







@dataclass
class       __lowercase					:
	_lowerCamelCase       			=  field(metadata={'''help''': '''The name of the task to train on: ''' + ''', '''.join(glue_processors.keys()    )}    )
	_lowerCamelCase       			=  field(
	    metadata={'''help''': '''The input data dir. Should contain the .tsv files (or other data files) for the task.'''}    )
	_lowerCamelCase       			=  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.'''
	        )
	    }   ,				)
	_lowerCamelCase       			=  field(
	    default=_A   ,				metadata={'''help''': '''Overwrite the cached training and evaluation sets'''}    )

	def      __UpperCamelCase							(      self   :						Optional[Any]):
			UpperCamelCase__				:					str					=					self.task_name.lower()







class       __lowercase					(_A    ):
	_lowerCamelCase       			=  '''train'''
	_lowerCamelCase       			=  '''dev'''
	_lowerCamelCase       			=  '''test'''







class       __lowercase					(_A    ):
	_lowerCamelCase       			=  42
	_lowerCamelCase       			=  42
	_lowerCamelCase       			=  42

	def __init__(      self   :						Tuple  ,					UpperCAmelCase_   :						GlueDataTrainingArguments  ,					UpperCAmelCase_   :						PreTrainedTokenizerBase  ,					UpperCAmelCase_   :						Optional[int] = None  ,					UpperCAmelCase_   :						Union[str, Split] = Split.train  ,					UpperCAmelCase_   :						Optional[str] = None  ,					):
			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'  ,					UpperCamelCase__  ,					)
			UpperCamelCase__				:					Any					=					args
			UpperCamelCase__				:					Any					=					glue_processors[args.task_name]()
			UpperCamelCase__				:					Any					=					glue_output_modes[args.task_name]
			if isinstance(UpperCamelCase__  ,					UpperCamelCase__):
					try:
							UpperCamelCase__				:					str					=					Split[mode]
					except KeyError:
							raise KeyError('mode is not a valid split name')
							# Load data features from cache or dataset file
			UpperCamelCase__				:					List[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}'  ,					)
			UpperCamelCase__				:					Any					=					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)
					UpperCamelCase__,	UpperCamelCase__				:					List[Any]					=					label_list[2], label_list[1]
			UpperCamelCase__				:					List[str]					=					label_list

			# Make sure only the first process in distributed training processes the dataset,
			# and the others will use the cache.
			UpperCamelCase__				:					Any					=					cached_features_file + '.lock'
			with FileLock(UpperCamelCase__):
					if os.path.exists(UpperCamelCase__) and not args.overwrite_cache:
							UpperCamelCase__				:					Union[str, Any]					=					time.time()
							UpperCamelCase__				:					List[Any]					=					torch.load(UpperCamelCase__)
							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:
									UpperCamelCase__				:					Union[str, Any]					=					self.processor.get_dev_examples(args.data_dir)
							elif mode == Split.test:
									UpperCamelCase__				:					int					=					self.processor.get_test_examples(args.data_dir)
							else:
									UpperCamelCase__				:					int					=					self.processor.get_train_examples(args.data_dir)
							if limit_length is not None:
									UpperCamelCase__				:					Tuple					=					examples[:limit_length]
							UpperCamelCase__				:					Optional[Any]					=					glue_convert_examples_to_features(
							    UpperCamelCase__  ,					UpperCamelCase__  ,					max_length=args.max_seq_length  ,					label_list=UpperCamelCase__  ,					output_mode=self.output_mode  ,					)
							UpperCamelCase__				:					Any					=					time.time()
							torch.save(self.features  ,					UpperCamelCase__)
							# ^ 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   :						List[Any]  ,					UpperCAmelCase_   :						List[str]):
			return self.features[i]





	def      __UpperCamelCase							(      self   :						Union[str, Any]):
			return self.label_list












'''simple docstring'''




import numpy as np
from PIL import Image







def       __UpperCAmelCase						(  lowerCamelCase_     ,      lowerCamelCase_     ,      lowerCamelCase_)							->     np.ndarray:
		UpperCamelCase__				:					List[Any]					=					np.array(lowerCamelCase_)
		if arr.shape[0] != arr.shape[1]:
				raise ValueError('The input array is not a square matrix')
		UpperCamelCase__				:					Tuple					=					0
		UpperCamelCase__				:					int					=					0
		UpperCamelCase__				:					Optional[int]					=					0
		UpperCamelCase__				:					str					=					0

		# compute the shape of the output matrix
		UpperCamelCase__				:					int					=					(arr.shape[0] - size) // stride + 1
		# initialize the output matrix with zeros of shape maxpool_shape
		UpperCamelCase__				:					Dict					=					np.zeros((maxpool_shape, maxpool_shape))

		while i < arr.shape[0]:
				if i + size > arr.shape[0]:
						# if the end of the matrix is reached, break
						break
				while j < arr.shape[1]:
						# if the end of the matrix is reached, break
						if j + size > arr.shape[1]:
								break
						# compute the maximum of the pooling matrix
						UpperCamelCase__				:					Dict					=					np.max(arr[i : i + size, j : j + size])
						# shift the pooling matrix by stride of column pixels
						j += stride
						mat_j += 1

				# shift the pooling matrix by stride of row pixels
				i += stride
				mat_i += 1

				# reset the column index to 0
				UpperCamelCase__				:					List[Any]					=					0
				UpperCamelCase__				:					Optional[int]					=					0

		return updated_arr







def       __UpperCAmelCase						(  lowerCamelCase_     ,      lowerCamelCase_     ,      lowerCamelCase_)							->     np.ndarray:
		UpperCamelCase__				:					Tuple					=					np.array(lowerCamelCase_)
		if arr.shape[0] != arr.shape[1]:
				raise ValueError('The input array is not a square matrix')
		UpperCamelCase__				:					Optional[int]					=					0
		UpperCamelCase__				:					int					=					0
		UpperCamelCase__				:					List[str]					=					0
		UpperCamelCase__				:					List[Any]					=					0

		# compute the shape of the output matrix
		UpperCamelCase__				:					str					=					(arr.shape[0] - size) // stride + 1
		# initialize the output matrix with zeros of shape avgpool_shape
		UpperCamelCase__				:					Union[str, Any]					=					np.zeros((avgpool_shape, avgpool_shape))

		while i < arr.shape[0]:
				# if the end of the matrix is reached, break
				if i + size > arr.shape[0]:
						break
				while j < arr.shape[1]:
						# if the end of the matrix is reached, break
						if j + size > arr.shape[1]:
								break
						# compute the average of the pooling matrix
						UpperCamelCase__				:					List[Any]					=					int(np.average(arr[i : i + size, j : j + size]))
						# shift the pooling matrix by stride of column pixels
						j += stride
						mat_j += 1

				# shift the pooling matrix by stride of row pixels
				i += stride
				mat_i += 1
				# reset the column index to 0
				UpperCamelCase__				:					Union[str, Any]					=					0
				UpperCamelCase__				:					Optional[Any]					=					0

		return updated_arr


# Main Function
if __name__ == "__main__":
		from doctest import testmod

		testmod(name='avgpooling', verbose=True)

		# Loading the image
		lowerCAmelCase__          =						Image.open('path_to_image')

		# Converting the image to numpy array and maxpooling, displaying the result
		# Ensure that the image is a square matrix

		Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show()

		# Converting the image to numpy array and averagepooling, displaying the result
		# Ensure that the image is a square matrix

		Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()




