






import warnings
from dataclasses import dataclass, field
from typing import Optional, Tuple

from .training_args import TrainingArguments
from .utils import cached_property, is_tf_available, logging, requires_backends


__lowerCamelCase						= logging.get_logger(__name__)

if is_tf_available():
						import tensorflow as tf

@dataclass
class      UpperCamelCase_							(				UpperCamelCase       ):
						lowercase									=  '''tf'''
						lowercase									=  field(
						    default=UpperCamelCase ,       metadata={'''help''': '''Name of TPU'''} ,       )

						lowercase									=  field(
						    default=UpperCamelCase ,       metadata={'''help''': '''Zone of TPU'''} ,       )

						lowercase									=  field(
						    default=UpperCamelCase ,       metadata={'''help''': '''Name of Cloud TPU-enabled project'''} ,       )

						lowercase									=  field(
						    default=1.0 ,       metadata={'''help''': '''Power for the Polynomial decay LR scheduler.'''} ,       )

						lowercase									=  field(default=UpperCamelCase ,       metadata={'''help''': '''Whether to activate the XLA compilation or not'''}       )




						@cached_property
						def      snake_case__(    self       )			->						Tuple["tf.distribute.Strategy", int]:
													requires_backends(self		,	['''tf''']       )
													logger.info('''Tensorflow: setting up strategy'''       )

													_a  :    int			=						tf.config.list_physical_devices('''GPU'''       )

													# Set to float16 at first
													if self.fpaa:
																				tf.keras.mixed_precision.set_global_policy('''mixed_float16'''       )

													if self.no_cuda:
																				_a  :    Union[str, Any]			=						tf.distribute.OneDeviceStrategy(device='''/cpu:0'''       )
													else:
																				try:
																											if self.tpu_name:
																																		_a  :    int			=						tf.distribute.cluster_resolver.TPUClusterResolver(
																																		    self.tpu_name		,	zone=self.tpu_zone		,	project=self.gcp_project       )
																											else:
																																		_a  :    List[str]			=						tf.distribute.cluster_resolver.TPUClusterResolver()
																				except ValueError:
																											if self.tpu_name:
																																		raise RuntimeError(F'Couldn\'t connect to TPU {self.tpu_name}!'       )
																											else:
																																		_a  :    List[Any]			=						None

																				if tpu:
																											# Set to bfloat16 in case of TPU
																											if self.fpaa:
																																		tf.keras.mixed_precision.set_global_policy('''mixed_bfloat16'''       )

																											tf.config.experimental_connect_to_cluster(lowercase       )
																											tf.tpu.experimental.initialize_tpu_system(lowercase       )

																											_a  :    Any			=						tf.distribute.TPUStrategy(lowercase       )

																				elif len(lowercase       ) == 0:
																											_a  :    int			=						tf.distribute.OneDeviceStrategy(device='''/cpu:0'''       )
																				elif len(lowercase       ) == 1:
																											_a  :    Any			=						tf.distribute.OneDeviceStrategy(device='''/gpu:0'''       )
																				elif len(lowercase       ) > 1:
																											# If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0`
																											_a  :    List[str]			=						tf.distribute.MirroredStrategy()
																				else:
																											raise ValueError('''Cannot find the proper strategy, please check your environment properties.'''       )

													return strategy




						@property
						def      snake_case__(    self       )			->						"tf.distribute.Strategy":
													requires_backends(self		,	['''tf''']       )
													return self._setup_strategy




						@property
						def      snake_case__(    self       )			->						int:
													requires_backends(self		,	['''tf''']       )
													return self._setup_strategy.num_replicas_in_sync




						@property
						def      snake_case__(    self       )			->						Dict:
													return False  # TF Logging is handled by Keras not the Trainer




						@property
						def      snake_case__(    self       )			->						int:
													if self.per_gpu_train_batch_size:
																				logger.warning(
																				    '''Using deprecated `--per_gpu_train_batch_size` argument which will be removed in a future '''
																				    '''version. Using `--per_device_train_batch_size` is preferred.'''       )
													_a  :    Union[str, Any]			=						self.per_gpu_train_batch_size or self.per_device_train_batch_size
													return per_device_batch_size * self.n_replicas




						@property
						def      snake_case__(    self       )			->						int:
													if self.per_gpu_eval_batch_size:
																				logger.warning(
																				    '''Using deprecated `--per_gpu_eval_batch_size` argument which will be removed in a future '''
																				    '''version. Using `--per_device_eval_batch_size` is preferred.'''       )
													_a  :    Tuple			=						self.per_gpu_eval_batch_size or self.per_device_eval_batch_size
													return per_device_batch_size * self.n_replicas







						@property
						def      snake_case__(    self       )			->						int:
													requires_backends(self		,	['''tf''']       )
													warnings.warn(
													    '''The n_gpu argument is deprecated and will be removed in a future version, use n_replicas instead.'''		,	lowercase		,	)
													return self._setup_strategy.num_replicas_in_sync







import textwrap

import pyarrow as pa
import pytest

from datasets import Features, Image
from datasets.packaged_modules.text.text import Text

from ..utils import require_pil






@pytest.fixture
def    UpperCamelCase__  (   UpperCAmelCase     )     ->		Union[str, Any]:







							"""simple docstring"""





							_a  :    Tuple			=						tmp_path / '''text.txt'''
							_a  :    Dict			=						textwrap.dedent(
							    '''\
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
        Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

        Second paragraph:
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
        Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
        '''     )
							with open(UpperCAmelCase    ,	'''w'''    ,	encoding='''utf-8'''     ) as f:
														f.write(UpperCAmelCase     )
							return str(UpperCAmelCase     )






@pytest.fixture
def    UpperCamelCase__  (   UpperCAmelCase    ,	UpperCAmelCase     )     ->		Optional[int]:







							"""simple docstring"""





							_a  :    List[Any]			=						tmp_path / '''text_with_image.txt'''
							with open(UpperCAmelCase    ,	'''w'''    ,	encoding='''utf-8'''     ) as f:
														f.write(UpperCAmelCase     )
							return str(UpperCAmelCase     )






@pytest.mark.parametrize('''keep_linebreaks'''    ,	[True, False]     )
def    UpperCamelCase__  (   UpperCAmelCase    ,	UpperCAmelCase     )     ->		Any:







							"""simple docstring"""





							with open(UpperCAmelCase    ,	encoding='''utf-8'''     ) as f:
														_a  :    str			=						f.read().splitlines(keepends=UpperCAmelCase     )
							_a  :    Tuple			=						Text(keep_linebreaks=UpperCAmelCase    ,	encoding='''utf-8'''     )
							_a  :    Optional[Any]			=						text._generate_tables([[text_file]]     )
							_a  :    str			=						pa.concat_tables([table for _, table in generator]     ).to_pydict()['''text''']
							assert generated_content == expected_content






@require_pil
def    UpperCamelCase__  (   UpperCAmelCase     )     ->		List[str]:







							"""simple docstring"""





							with open(UpperCAmelCase    ,	encoding='''utf-8'''     ) as f:
														_a  :    str			=						f.read().splitlines()[0]
							_a  :    Dict			=						Text(encoding='''utf-8'''    ,	features=Features({'''image''': Image()}     )     )
							_a  :    str			=						text._generate_tables([[text_file_with_image]]     )
							_a  :    int			=						pa.concat_tables([table for _, table in generator]     )
							assert pa_table.schema.field('''image'''     ).type == Image()()
							_a  :    Optional[int]			=						pa_table.to_pydict()['''image''']
							assert generated_content == [{"path": image_file, "bytes": None}]







@pytest.mark.parametrize('''sample_by'''    ,	['''line''', '''paragraph''', '''document''']     )
def    UpperCamelCase__  (   UpperCAmelCase    ,	UpperCAmelCase     )     ->		Optional[Any]:







							"""simple docstring"""





							with open(UpperCAmelCase    ,	encoding='''utf-8'''     ) as f:
														_a  :    Any			=						f.read()
							if sample_by == "line":
														_a  :    Any			=						expected_content.splitlines()
							elif sample_by == "paragraph":
														_a  :    Tuple			=						expected_content.split('''\n\n'''     )
							elif sample_by == "document":
														_a  :    Dict			=						[expected_content]
							_a  :    Dict			=						Text(sample_by=UpperCAmelCase    ,	encoding='''utf-8'''    ,	chunksize=100     )
							_a  :    Optional[int]			=						text._generate_tables([[text_file]]     )
							_a  :    List[Any]			=						pa.concat_tables([table for _, table in generator]     ).to_pydict()['''text''']
							assert generated_content == expected_content