





import time
from dataclasses import dataclass
from multiprocessing import Pool
from unittest import TestCase
from unittest.mock import patch

import multiprocess
import numpy as np
import pytest

from datasets.utils.py_utils import (
    NestedDataStructure,
    asdict,
    iflatmap_unordered,
    map_nested,
    temp_seed,
    temporary_assignment,
    zip_dict,
)

from .utils import require_tf, require_torch







def    A				(							UpperCAmelCase				):  # picklable for multiprocessing
					return x.sum()







def    A				(							UpperCAmelCase				):  # picklable for multiprocessing
					return i + 1






@dataclass
class        _a:
		lowerCamelCase__     :int
		lowerCamelCase__     :str






class        _a(    __A    ):







		def        lowercase       (    self				)      ->      Optional[Any]:


							'''simple docstring'''

							_snake_case       :					List[Any]				       =   {}
							_snake_case       :					Tuple				       =   []
							_snake_case       :					int				       =   1
							_snake_case       :					Any				       =   [1, 2]
							_snake_case       :					str				       =   {"a": 1, "b": 2}
							_snake_case       :					str				       =   {"a": [1, 2], "b": [3, 4]}
							_snake_case       :					Tuple				       =   {"a": {"1": 1}, "b": 2}
							_snake_case       :					str				       =   {"a": 1, "b": 2, "c": 3, "d": 4}
							_snake_case       :					str				       =   {}
							_snake_case       :					Optional[Any]				       =   []
							_snake_case       :					str				       =   2
							_snake_case       :					List[Any]				       =   [2, 3]
							_snake_case       :					Any				       =   {"a": 2, "b": 3}
							_snake_case       :					Any				       =   {"a": [2, 3], "b": [4, 5]}
							_snake_case       :					int				       =   {"a": {"1": 2}, "b": 3}
							_snake_case       :					Dict				       =   {"a": 2, "b": 3, "c": 4, "d": 5}
							self.assertEqual(map_nested(__snake_case ,						__snake_case				) ,						__snake_case				)
							self.assertEqual(map_nested(__snake_case ,						__snake_case				) ,						__snake_case				)
							self.assertEqual(map_nested(__snake_case ,						__snake_case				) ,						__snake_case				)
							self.assertEqual(map_nested(__snake_case ,						__snake_case				) ,						__snake_case				)
							self.assertEqual(map_nested(__snake_case ,						__snake_case				) ,						__snake_case				)
							self.assertEqual(map_nested(__snake_case ,						__snake_case				) ,						__snake_case				)
							self.assertEqual(map_nested(__snake_case ,						__snake_case				) ,						__snake_case				)
							self.assertEqual(map_nested(__snake_case ,						__snake_case				) ,						__snake_case				)

							_snake_case       :					Dict				       =   2
							self.assertEqual(map_nested(__snake_case ,						__snake_case ,						num_proc=__snake_case				) ,						__snake_case				)
							self.assertEqual(map_nested(__snake_case ,						__snake_case ,						num_proc=__snake_case				) ,						__snake_case				)
							self.assertEqual(map_nested(__snake_case ,						__snake_case ,						num_proc=__snake_case				) ,						__snake_case				)
							self.assertEqual(map_nested(__snake_case ,						__snake_case ,						num_proc=__snake_case				) ,						__snake_case				)
							self.assertEqual(map_nested(__snake_case ,						__snake_case ,						num_proc=__snake_case				) ,						__snake_case				)
							self.assertEqual(map_nested(__snake_case ,						__snake_case ,						num_proc=__snake_case				) ,						__snake_case				)
							self.assertEqual(map_nested(__snake_case ,						__snake_case ,						num_proc=__snake_case				) ,						__snake_case				)
							self.assertEqual(map_nested(__snake_case ,						__snake_case ,						num_proc=__snake_case				) ,						__snake_case				)

							_snake_case       :					Union[str, Any]				       =   {"a": np.eye(2				), "b": np.zeros(3				), "c": np.ones(2				)}
							_snake_case       :					Dict				       =   {"a": 2, "b": 0, "c": 2}
							_snake_case       :					Union[str, Any]				       =   {
							    "a": np.eye(2				).astype(__snake_case				),
							    "b": np.zeros(3				).astype(__snake_case				),
							    "c": np.ones(2				).astype(__snake_case				),
							}
							self.assertEqual(map_nested(__snake_case ,						__snake_case ,						map_numpy=__snake_case				) ,						__snake_case				)
							self.assertEqual(
							    {k: v.tolist() for k, v in map_nested(__snake_case ,						__snake_case ,						map_numpy=__snake_case				).items()} ,						{k: v.tolist() for k, v in expected_map_nested_sna_int.items()} ,						)
							self.assertEqual(map_nested(__snake_case ,						__snake_case ,						map_numpy=__snake_case ,						num_proc=__snake_case				) ,						__snake_case				)
							self.assertEqual(
							    {k: v.tolist() for k, v in map_nested(__snake_case ,						__snake_case ,						map_numpy=__snake_case ,						num_proc=__snake_case				).items()} ,						{k: v.tolist() for k, v in expected_map_nested_sna_int.items()} ,						)
							with self.assertRaises(__snake_case				):  # can't pickle a local lambda
												map_nested(lambda __snake_case				: x + 1 ,						__snake_case ,						num_proc=__snake_case				)







		def        lowercase       (    self				)      ->      Dict:


							'''simple docstring'''

							_snake_case       :					str				       =   {"a": 1, "b": 2}
							_snake_case       :					Union[str, Any]				       =   {"a": 3, "b": 4}
							_snake_case       :					int				       =   {"a": 5, "b": 6}
							_snake_case       :					Optional[Any]				       =   sorted([("a", (1, 3, 5)), ("b", (2, 4, 6))]				)
							self.assertEqual(sorted(zip_dict(__snake_case ,						__snake_case ,						__snake_case				)				) ,						__snake_case				)







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


							'''simple docstring'''

							class        _a:
									lowerCamelCase__     :str   				=		'bar'






							_snake_case       :					Optional[Any]				       =   Foo()
							self.assertEqual(foo.my_attr ,						"bar"				)
							with temporary_assignment(__snake_case ,						"my_attr" ,						"BAR"				):
												self.assertEqual(foo.my_attr ,						"BAR"				)
							self.assertEqual(foo.my_attr ,						"bar"				)







@pytest.mark.parametrize(
    "iterable_length, num_proc, expected_num_proc"  ,  [
        (1, None, 1),
        (1, 1, 1),
        (2, None, 1),
        (2, 1, 1),
        (2, 2, 1),
        (2, 3, 1),
        (3, 2, 1),
        (16, 16, 16),
        (16, 17, 16),
        (17, 16, 16),
    ]  ,  )
def    A				(							UpperCAmelCase  ,  UpperCAmelCase  ,  UpperCAmelCase				):
					with patch("datasets.utils.py_utils._single_map_nested"				) as mock_single_map_nested, patch(
					    "datasets.parallel.parallel.Pool"				) as mock_multiprocessing_pool:
										_snake_case       :					Any				       =   {F"""{i}""": i for i in range(UpperCAmelCase				)}
										_snake_case       :					Optional[Any]				       =   map_nested(lambda UpperCAmelCase				: x + 10  ,  UpperCAmelCase  ,  num_proc=UpperCAmelCase  ,  parallel_min_length=16				)
										if expected_num_proc == 1:
															assert mock_single_map_nested.called
															assert not mock_multiprocessing_pool.called
										else:
															assert not mock_single_map_nested.called
															assert mock_multiprocessing_pool.called
															assert mock_multiprocessing_pool.call_args[0][0] == expected_num_proc






class        _a(    __A    ):







		@require_tf
		def        lowercase       (    self				)      ->      List[str]:


							'''simple docstring'''

							import tensorflow as tf
							from tensorflow.keras import layers

							_snake_case       :					int				       =   layers.Dense(2				)

							def gen_random_output():
												_snake_case       :					Dict				       =   tf.random.uniform((1, 3)				)
												return model(__snake_case				).numpy()

							with temp_seed(4_2 ,						set_tensorflow=__snake_case				):
												_snake_case       :					int				       =   gen_random_output()
							with temp_seed(4_2 ,						set_tensorflow=__snake_case				):
												_snake_case       :					List[Any]				       =   gen_random_output()
							_snake_case       :					List[Any]				       =   gen_random_output()

							np.testing.assert_equal(__snake_case ,						__snake_case				)
							self.assertGreater(np.abs(outa - outa				).sum() ,						0				)







		@require_torch
		def        lowercase       (    self				)      ->      str:


							'''simple docstring'''

							import torch

							def gen_random_output():
												_snake_case       :					Any				       =   torch.nn.Linear(3 ,						2				)
												_snake_case       :					Dict				       =   torch.rand(1 ,						3				)
												return model(__snake_case				).detach().numpy()

							with temp_seed(4_2 ,						set_pytorch=__snake_case				):
												_snake_case       :					Any				       =   gen_random_output()
							with temp_seed(4_2 ,						set_pytorch=__snake_case				):
												_snake_case       :					Optional[Any]				       =   gen_random_output()
							_snake_case       :					List[str]				       =   gen_random_output()

							np.testing.assert_equal(__snake_case ,						__snake_case				)
							self.assertGreater(np.abs(outa - outa				).sum() ,						0				)







		def        lowercase       (    self				)      ->      str:


							'''simple docstring'''

							def gen_random_output():
												return np.random.rand(1 ,						3				)

							with temp_seed(4_2				):
												_snake_case       :					Any				       =   gen_random_output()
							with temp_seed(4_2				):
												_snake_case       :					Optional[Any]				       =   gen_random_output()
							_snake_case       :					int				       =   gen_random_output()

							np.testing.assert_equal(__snake_case ,						__snake_case				)
							self.assertGreater(np.abs(outa - outa				).sum() ,						0				)







@pytest.mark.parametrize("input_data"  ,  [{}]				)
def    A				(							UpperCAmelCase				):
					_snake_case       :					List[Any]				       =   NestedDataStructure(UpperCAmelCase				).data
					assert output_data == input_data







@pytest.mark.parametrize(
    "data, expected_output"  ,  [
        ({}, []),
        ([], []),
        ("foo", ["foo"]),
        (["foo", "bar"], ["foo", "bar"]),
        ([["foo", "bar"]], ["foo", "bar"]),
        ([[["foo"], ["bar"]]], ["foo", "bar"]),
        ([[["foo"], "bar"]], ["foo", "bar"]),
        ({"a": 1, "b": 2}, [1, 2]),
        ({"a": [1, 2], "b": [3, 4]}, [1, 2, 3, 4]),
        ({"a": [[1, 2]], "b": [[3, 4]]}, [1, 2, 3, 4]),
        ({"a": [[1, 2]], "b": [3, 4]}, [1, 2, 3, 4]),
        ({"a": [[[1], [2]]], "b": [[[3], [4]]]}, [1, 2, 3, 4]),
        ({"a": [[[1], [2]]], "b": [[3, 4]]}, [1, 2, 3, 4]),
        ({"a": [[[1], [2]]], "b": [3, 4]}, [1, 2, 3, 4]),
        ({"a": [[[1], [2]]], "b": [3, [4]]}, [1, 2, 3, 4]),
        ({"a": {"1": 1}, "b": 2}, [1, 2]),
        ({"a": {"1": [1]}, "b": 2}, [1, 2]),
        ({"a": {"1": [1]}, "b": [2]}, [1, 2]),
    ]  ,  )
def    A				(							UpperCAmelCase  ,  UpperCAmelCase				):
					_snake_case       :					Dict				       =   NestedDataStructure(UpperCAmelCase				).flatten()
					assert output == expected_output







def    A				(							):
					_snake_case       :					Any				       =   A(x=1  ,  y="foobar"				)
					_snake_case       :					Union[str, Any]				       =   {"x": 1, "y": "foobar"}
					assert asdict(UpperCAmelCase				) == expected_output

					_snake_case       :					Tuple				       =   {"a": {"b": A(x=10  ,  y="foo"				)}, "c": [A(x=20  ,  y="bar"				)]}
					_snake_case       :					str				       =   {"a": {"b": {"x": 10, "y": "foo"}}, "c": [{"x": 20, "y": "bar"}]}
					assert asdict(UpperCAmelCase				) == expected_output

					with pytest.raises(UpperCAmelCase				):
										asdict([1, A(x=10  ,  y="foo"				)]				)







def    A				(							UpperCAmelCase				):
					return text.split()







def    A				(							UpperCAmelCase				):
					yield (time.time(), content)
					time.sleep(2				)
					yield (time.time(), content)







def    A				(							):
					with Pool(2				) as pool:
										_snake_case       :					List[Any]				       =   list(iflatmap_unordered(UpperCAmelCase  ,  _split_text  ,  kwargs_iterable=[{"text": "hello there"}] * 10				)				)
										assert out.count("hello"				) == 10
										assert out.count("there"				) == 10
										assert len(UpperCAmelCase				) == 20

					# check multiprocess from pathos (uses dill for pickling)
					with multiprocess.Pool(2				) as pool:
										_snake_case       :					Any				       =   list(iflatmap_unordered(UpperCAmelCase  ,  _split_text  ,  kwargs_iterable=[{"text": "hello there"}] * 10				)				)
										assert out.count("hello"				) == 10
										assert out.count("there"				) == 10
										assert len(UpperCAmelCase				) == 20

					# check that we get items as fast as possible
					with Pool(2				) as pool:
										_snake_case       :					Dict				       =   []
										for yield_time, content in iflatmap_unordered(
										    UpperCAmelCase  ,  _aseconds_generator_of_aitems_with_timing  ,  kwargs_iterable=[{"content": "a"}, {"content": "b"}]				):
															assert yield_time < time.time() + 0.1, "we should each item directly after it was yielded"
															out.append(UpperCAmelCase				)
										assert out.count("a"				) == 2
										assert out.count("b"				) == 2
										assert len(UpperCAmelCase				) == 4






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 :Tuple     =    logging.get_logger(__name__)






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







		def        lowercase       (    self				)      ->      Optional[Any]:


							'''simple docstring'''

							_snake_case       :					Dict				       =   self.task_name.lower()






class        _a(    __A    ):
		lowerCamelCase__     :Optional[Any]   				=		'train'
		lowerCamelCase__     :List[str]   				=		'dev'
		lowerCamelCase__     :Any   				=		'test'






class        _a(    __A    ):
		lowerCamelCase__     :GlueDataTrainingArguments
		lowerCamelCase__     :str
		lowerCamelCase__     :List[InputFeatures]







		def __init__(    self ,						__snake_case ,						__snake_case ,						__snake_case = None ,						__snake_case = Split.train ,						__snake_case = None ,						)      ->      Any:


							'''simple docstring'''

							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" ,						__snake_case ,						)
							_snake_case       :					Optional[Any]				       =   args
							_snake_case       :					Optional[int]				       =   glue_processors[args.task_name]()
							_snake_case       :					int				       =   glue_output_modes[args.task_name]
							if isinstance(__snake_case ,						__snake_case				):
												try:
																	_snake_case       :					Tuple				       =   Split[mode]
												except KeyError:
																	raise KeyError("mode is not a valid split name"				)
        # Load data features from cache or dataset file
							_snake_case       :					List[str]				       =   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}""" ,						)
							_snake_case       :					List[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)
												_snake_case       , _snake_case       :					int				       =   label_list[2], label_list[1]
							_snake_case       :					str				       =   label_list

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


							'''simple docstring'''

							return len(self.features				)







		def __getitem__(    self ,						__snake_case				)      ->      InputFeatures:


							'''simple docstring'''

							return self.features[i]







		def        lowercase       (    self				)      ->      Optional[Any]:


							'''simple docstring'''

							return self.label_list