






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		(					lowercase__  :  str  )		-> Any:  # picklable for multiprocessing
	return x.sum()




def 				A		(					lowercase__  :  Dict  )		-> List[Any]:  # picklable for multiprocessing
	return i + 1

@dataclass
class        lowerCAmelCase_				:







				"""simple docstring"""




				_snake_case				:   int
				_snake_case				:   str

class        lowerCAmelCase_				(      lowercase	):







				"""simple docstring"""




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

					UpperCamelCase__ :Dict						=      2
					self.assertEqual(map_nested(lowerCamelCase__  ,     lowerCamelCase__  ,     num_proc=lowerCamelCase__     )  ,     lowerCamelCase__     )
					self.assertEqual(map_nested(lowerCamelCase__  ,     lowerCamelCase__  ,     num_proc=lowerCamelCase__     )  ,     lowerCamelCase__     )
					self.assertEqual(map_nested(lowerCamelCase__  ,     lowerCamelCase__  ,     num_proc=lowerCamelCase__     )  ,     lowerCamelCase__     )
					self.assertEqual(map_nested(lowerCamelCase__  ,     lowerCamelCase__  ,     num_proc=lowerCamelCase__     )  ,     lowerCamelCase__     )
					self.assertEqual(map_nested(lowerCamelCase__  ,     lowerCamelCase__  ,     num_proc=lowerCamelCase__     )  ,     lowerCamelCase__     )
					self.assertEqual(map_nested(lowerCamelCase__  ,     lowerCamelCase__  ,     num_proc=lowerCamelCase__     )  ,     lowerCamelCase__     )
					self.assertEqual(map_nested(lowerCamelCase__  ,     lowerCamelCase__  ,     num_proc=lowerCamelCase__     )  ,     lowerCamelCase__     )
					self.assertEqual(map_nested(lowerCamelCase__  ,     lowerCamelCase__  ,     num_proc=lowerCamelCase__     )  ,     lowerCamelCase__     )

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







				def 				__a   ( self     :Tuple     ):
					UpperCamelCase__ :List[str]						=      {"""a""": 1, """b""": 2}
					UpperCamelCase__ :Tuple						=      {"""a""": 3, """b""": 4}
					UpperCamelCase__ :Optional[Any]						=      {"""a""": 5, """b""": 6}
					UpperCamelCase__ :Union[str, Any]						=      sorted([("""a""", (1, 3, 5)), ("""b""", (2, 4, 6))]     )
					self.assertEqual(sorted(zip_dict(lowerCamelCase__  ,     lowerCamelCase__  ,     lowerCamelCase__     )     )  ,     lowerCamelCase__     )







				def 				__a   ( self     :Optional[Any]     ):

					class        lowerCAmelCase_				:







									"""simple docstring"""




									_snake_case				:   List[str]        =			"""bar"""

					UpperCamelCase__ :List[str]						=      Foo()
					self.assertEqual(foo.my_attr  ,     """bar"""     )
					with temporary_assignment(lowerCamelCase__  ,     """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		(					lowercase__  :  str ,		lowercase__  :  Any ,		lowercase__  :  Tuple  )		-> Optional[int]:
	with patch("""datasets.utils.py_utils._single_map_nested"""  ) as mock_single_map_nested, patch(
	    """datasets.parallel.parallel.Pool"""  ) as mock_multiprocessing_pool:
		UpperCamelCase__ :Optional[int]						=      {f"""{i}""": i for i in range(lowercase__  )}
		UpperCamelCase__ :Any						=      map_nested(lambda lowercase__  : x + 10 ,		lowercase__ ,		num_proc=lowercase__ ,		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        lowerCAmelCase_				(      lowercase	):







				"""simple docstring"""




				@require_tf
				def 				__a   ( self     :str     ):
					import tensorflow as tf
					from tensorflow.keras import layers

					UpperCamelCase__ :List[Any]						=      layers.Dense(2     )

					def gen_random_output():
						UpperCamelCase__ :str						=      tf.random.uniform((1, 3)     )
						return model(lowerCamelCase__     ).numpy()

					with temp_seed(42  ,     set_tensorflow=lowerCamelCase__     ):
						UpperCamelCase__ :List[Any]						=      gen_random_output()
					with temp_seed(42  ,     set_tensorflow=lowerCamelCase__     ):
						UpperCamelCase__ :Tuple						=      gen_random_output()
					UpperCamelCase__ :Any						=      gen_random_output()

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







				@require_torch
				def 				__a   ( self     :Union[str, Any]     ):
					import torch

					def gen_random_output():
						UpperCamelCase__ :Optional[int]						=      torch.nn.Linear(3  ,     2     )
						UpperCamelCase__ :List[Any]						=      torch.rand(1  ,     3     )
						return model(lowerCamelCase__     ).detach().numpy()

					with temp_seed(42  ,     set_pytorch=lowerCamelCase__     ):
						UpperCamelCase__ :Optional[int]						=      gen_random_output()
					with temp_seed(42  ,     set_pytorch=lowerCamelCase__     ):
						UpperCamelCase__ :Union[str, Any]						=      gen_random_output()
					UpperCamelCase__ :Optional[Any]						=      gen_random_output()

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







				def 				__a   ( self     :List[Any]     ):
					def gen_random_output():
						return np.random.rand(1  ,     3     )

					with temp_seed(42     ):
						UpperCamelCase__ :Optional[int]						=      gen_random_output()
					with temp_seed(42     ):
						UpperCamelCase__ :str						=      gen_random_output()
					UpperCamelCase__ :Any						=      gen_random_output()

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




@pytest.mark.parametrize("""input_data""" ,		[{}]  )
def 				A		(					lowercase__  :  Dict  )		-> Union[str, Any]:
	UpperCamelCase__ :Tuple						=      NestedDataStructure(lowercase__  ).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		(					lowercase__  :  str ,		lowercase__  :  Union[str, Any]  )		-> List[Any]:
	UpperCamelCase__ :str						=      NestedDataStructure(lowercase__  ).flatten()
	assert output == expected_output




def 				A		(					)		-> Optional[Any]:
	UpperCamelCase__ :Optional[int]						=      A(x=1 ,		y="""foobar"""  )
	UpperCamelCase__ :Dict						=      {"""x""": 1, """y""": """foobar"""}
	assert asdict(lowercase__  ) == expected_output

	UpperCamelCase__ :Union[str, Any]						=      {"""a""": {"""b""": A(x=10 ,		y="""foo"""  )}, """c""": [A(x=20 ,		y="""bar"""  )]}
	UpperCamelCase__ :Dict						=      {"""a""": {"""b""": {"""x""": 10, """y""": """foo"""}}, """c""": [{"""x""": 20, """y""": """bar"""}]}
	assert asdict(lowercase__  ) == expected_output

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




def 				A		(					lowercase__  :  str  )		-> List[str]:
	return text.split()




def 				A		(					lowercase__  :  Any  )		-> str:
	yield (time.time(), content)
	time.sleep(2  )
	yield (time.time(), content)




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

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

	# check that we get items as fast as possible
	with Pool(2  ) as pool:
		UpperCamelCase__ :Tuple						=      []
		for yield_time, content in iflatmap_unordered(
		    lowercase__ ,		_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(lowercase__  )
		assert out.count("""a"""  ) == 2
		assert out.count("""b"""  ) == 2
		assert len(lowercase__  ) == 4





import os
from argparse import ArgumentParser, Namespace

from ..data import SingleSentenceClassificationProcessor as Processor
from ..pipelines import TextClassificationPipeline
from ..utils import is_tf_available, is_torch_available, logging
from . import BaseTransformersCLICommand


if not is_tf_available() and not is_torch_available():
				raise RuntimeError("At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training")

# TF training parameters
SCREAMING_SNAKE_CASE__     :     Union[str, Any]		    =       False
SCREAMING_SNAKE_CASE__     :     Optional[int]		    =       False

def lowercase    (  SCREAMING_SNAKE_CASE )			->							List[Any]:


			'''simple docstring'''







			return TrainCommand(SCREAMING_SNAKE_CASE )



class       a_       (     SCREAMING_SNAKE_CASE__     ):





	@staticmethod
	def 						A_(							SCREAMING_SNAKE_CASE      )  ->					Optional[int]:




				"""simple docstring"""



				SCREAMING_SNAKE_CASE_								=						parser.add_parser('train'      ,     help='CLI tool to train a model on a task.'      )

				train_parser.add_argument(
				    '--train_data'      ,     type=SCREAMING_SNAKE_CASE      ,     required=SCREAMING_SNAKE_CASE      ,     help='path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.'      ,     )
				train_parser.add_argument(
				    '--column_label'      ,     type=SCREAMING_SNAKE_CASE      ,     default=0      ,     help='Column of the dataset csv file with example labels.'      )
				train_parser.add_argument(
				    '--column_text'      ,     type=SCREAMING_SNAKE_CASE      ,     default=1      ,     help='Column of the dataset csv file with example texts.'      )
				train_parser.add_argument(
				    '--column_id'      ,     type=SCREAMING_SNAKE_CASE      ,     default=2      ,     help='Column of the dataset csv file with example ids.'      )
				train_parser.add_argument(
				    '--skip_first_row'      ,     action='store_true'      ,     help='Skip the first row of the csv file (headers).'      )

				train_parser.add_argument('--validation_data'      ,     type=SCREAMING_SNAKE_CASE      ,     default=''      ,     help='path to validation dataset.'      )
				train_parser.add_argument(
				    '--validation_split'      ,     type=SCREAMING_SNAKE_CASE      ,     default=0.1      ,     help='if validation dataset is not provided, fraction of train dataset to use as validation dataset.'      ,     )

				train_parser.add_argument('--output'      ,     type=SCREAMING_SNAKE_CASE      ,     default='./'      ,     help='path to saved the trained model.'      )

				train_parser.add_argument(
				    '--task'      ,     type=SCREAMING_SNAKE_CASE      ,     default='text_classification'      ,     help='Task to train the model on.'      )
				train_parser.add_argument(
				    '--model'      ,     type=SCREAMING_SNAKE_CASE      ,     default='bert-base-uncased'      ,     help='Model\'s name or path to stored model.'      )
				train_parser.add_argument('--train_batch_size'      ,     type=SCREAMING_SNAKE_CASE      ,     default=32      ,     help='Batch size for training.'      )
				train_parser.add_argument('--valid_batch_size'      ,     type=SCREAMING_SNAKE_CASE      ,     default=64      ,     help='Batch size for validation.'      )
				train_parser.add_argument('--learning_rate'      ,     type=SCREAMING_SNAKE_CASE      ,     default=3e-5      ,     help='Learning rate.'      )
				train_parser.add_argument('--adam_epsilon'      ,     type=SCREAMING_SNAKE_CASE      ,     default=1e-08      ,     help='Epsilon for Adam optimizer.'      )
				train_parser.set_defaults(func=SCREAMING_SNAKE_CASE      )





	def __init__(							self      ,     SCREAMING_SNAKE_CASE      )  ->					List[Any]:




				"""simple docstring"""



				SCREAMING_SNAKE_CASE_								=						logging.get_logger('transformers-cli/training'      )

				SCREAMING_SNAKE_CASE_								=						'tf' if is_tf_available() else 'torch'

				os.makedirs(args.output      ,     exist_ok=SCREAMING_SNAKE_CASE      )
				SCREAMING_SNAKE_CASE_								=						args.output

				SCREAMING_SNAKE_CASE_								=						args.column_label
				SCREAMING_SNAKE_CASE_								=						args.column_text
				SCREAMING_SNAKE_CASE_								=						args.column_id

				self.logger.info(f'Loading {args.task} pipeline for {args.model}'      )
				if args.task == "text_classification":
							SCREAMING_SNAKE_CASE_								=						TextClassificationPipeline.from_pretrained(args.model      )
				elif args.task == "token_classification":
							raise NotImplementedError
				elif args.task == "question_answering":
							raise NotImplementedError

				self.logger.info(f'Loading dataset from {args.train_data}'      )
				SCREAMING_SNAKE_CASE_								=						Processor.create_from_csv(
				    args.train_data      ,     column_label=args.column_label      ,     column_text=args.column_text      ,     column_id=args.column_id      ,     skip_first_row=args.skip_first_row      ,     )
				SCREAMING_SNAKE_CASE_								=						None
				if args.validation_data:
							self.logger.info(f'Loading validation dataset from {args.validation_data}'      )
							SCREAMING_SNAKE_CASE_								=						Processor.create_from_csv(
							    args.validation_data      ,     column_label=args.column_label      ,     column_text=args.column_text      ,     column_id=args.column_id      ,     skip_first_row=args.skip_first_row      ,     )

				SCREAMING_SNAKE_CASE_								=						args.validation_split
				SCREAMING_SNAKE_CASE_								=						args.train_batch_size
				SCREAMING_SNAKE_CASE_								=						args.valid_batch_size
				SCREAMING_SNAKE_CASE_								=						args.learning_rate
				SCREAMING_SNAKE_CASE_								=						args.adam_epsilon





	def 						A_(							self      )  ->					Dict:




				"""simple docstring"""



				if self.framework == "tf":
							return self.run_tf()
				return self.run_torch()





	def 						A_(							self      )  ->					Optional[int]:




				"""simple docstring"""



				raise NotImplementedError





	def 						A_(							self      )  ->					Dict:




				"""simple docstring"""



				self.pipeline.fit(
				    self.train_dataset      ,     validation_data=self.valid_dataset      ,     validation_split=self.validation_split      ,     learning_rate=self.learning_rate      ,     adam_epsilon=self.adam_epsilon      ,     train_batch_size=self.train_batch_size      ,     valid_batch_size=self.valid_batch_size      ,     )

				# Save trained pipeline
				self.pipeline.save_pretrained(self.output      )
