import random
from typing import List, Optional, Union

import numpy as np
import torch

from ..state import AcceleratorState
from .constants import CUDA_DISTRIBUTED_TYPES
from .dataclasses import DistributedType, RNGType
from .imports import is_npu_available, is_tpu_available, is_xpu_available


if is_tpu_available(check_device=False):
	import torch_xla.core.xla_model as xm




def   _UpperCamelCase   (			snake_case__,    snake_case__ = False							)						->   Optional[Any]:
							if device_specific:
														seed += AcceleratorState().process_index
							random.seed(snake_case__							)
							np.random.seed(snake_case__							)
							torch.manual_seed(snake_case__							)
							if is_xpu_available():
														torch.xpu.manual_seed_all(snake_case__							)
							elif is_npu_available():
														torch.npu.manual_seed_all(snake_case__							)
							else:
														torch.cuda.manual_seed_all(snake_case__							)
							# ^^ safe to call this function even if cuda is not available
							if is_tpu_available():
														xm.set_rng_state(snake_case__							)




def   _UpperCamelCase   (			snake_case__ = None,    snake_case__ = None							)						->   str:
							# Get the proper rng state
							if rng_type == RNGType.TORCH:
														__UpperCAmelCase						:			Dict         =   torch.get_rng_state()
							elif rng_type == RNGType.CUDA:
														__UpperCAmelCase						:			Union[str, Any]         =   torch.cuda.get_rng_state()
							elif rng_type == RNGType.XLA:
														assert is_tpu_available(), "Can't synchronize XLA seeds on an environment without TPUs."
														__UpperCAmelCase						:			Tuple         =   torch.tensor(xm.get_rng_state()							)
							elif rng_type == RNGType.NPU:
														assert is_npu_available(), "Can't synchronize NPU seeds on an environment without NPUs."
														__UpperCAmelCase						:			List[str]         =   torch.npu.get_rng_state()
							elif rng_type == RNGType.XPU:
														assert is_xpu_available(), "Can't synchronize XPU seeds on an environment without XPUs."
														__UpperCAmelCase						:			Optional[int]         =   torch.xpu.get_rng_state()
							elif rng_type == RNGType.GENERATOR:
														assert generator is not None, "Need a generator to synchronize its seed."
														__UpperCAmelCase						:			List[Any]         =   generator.get_state()

							# Broadcast the rng state from device 0 to other devices
							__UpperCAmelCase						:			Optional[int]         =   AcceleratorState()
							if state.distributed_type == DistributedType.TPU:
														__UpperCAmelCase						:			Any         =   rng_state.to(xm.xla_device()							)
														xm.collective_broadcast([rng_state]							)
														xm.mark_step()
														__UpperCAmelCase						:			Optional[int]         =   rng_state.cpu()
							elif (
							    state.distributed_type in CUDA_DISTRIBUTED_TYPES
							    or state.distributed_type == DistributedType.MULTI_NPU
							    or state.distributed_type == DistributedType.MULTI_XPU
							):
														__UpperCAmelCase						:			Optional[int]         =   rng_state.to(state.device							)
														torch.distributed.broadcast(snake_case__,    0							)
														__UpperCAmelCase						:			Tuple         =   rng_state.cpu()
							elif state.distributed_type == DistributedType.MULTI_CPU:
														torch.distributed.broadcast(snake_case__,    0							)

							# Set the broadcast rng state
							if rng_type == RNGType.TORCH:
														torch.set_rng_state(snake_case__							)
							elif rng_type == RNGType.CUDA:
														torch.cuda.set_rng_state(snake_case__							)
							elif rng_type == RNGType.NPU:
														torch.npu.set_rng_state(snake_case__							)
							elif rng_type == RNGType.XPU:
														torch.xpu.set_rng_state(snake_case__							)
							elif rng_type == RNGType.XLA:
														xm.set_rng_state(rng_state.item()							)
							elif rng_type == RNGType.GENERATOR:
														generator.set_state(snake_case__							)







def   _UpperCamelCase   (			snake_case__,    snake_case__ = None							)						->   str:
							for rng_type in rng_types:
														synchronize_rng_state(RNGType(snake_case__							),    generator=snake_case__							)





import itertools
from dataclasses import dataclass
from typing import Optional

import pyarrow as pa

import datasets
from datasets.table import table_cast


_snake_case			=						datasets.utils.logging.get_logger(__name__)




@dataclass
class 					_snake_case						(						datasets.BuilderConfig				):
					lowerCamelCase__:		Optional[datasets.Features]  =     None




class 					_snake_case						(						datasets.ArrowBasedBuilder				):
					lowerCamelCase__:		Union[str, Any]  =     ArrowConfig
					def    _lowerCamelCase (  self:				Optional[int]     )    ->				Optional[int]:
												return datasets.DatasetInfo(features=self.config.features     )
					def    _lowerCamelCase (  self:				List[Any]	,  __lowerCamelCase:				Tuple     )    ->				str:
												if not self.config.data_files:
																			raise ValueError(f'''At least one data file must be specified, but got data_files={self.config.data_files}'''     )
												__UpperCAmelCase						:			Dict         =   dl_manager.download_and_extract(self.config.data_files     )
												if isinstance(__lowerCamelCase	,  (str, list, tuple)     ):
																			__UpperCAmelCase						:			str         =   data_files
																			if isinstance(__lowerCamelCase	,  __lowerCamelCase     ):
																										__UpperCAmelCase						:			List[str]         =   [files]
																			# Use `dl_manager.iter_files` to skip hidden files in an extracted archive
																			__UpperCAmelCase						:			List[Any]         =   [dl_manager.iter_files(__lowerCamelCase     ) for file in files]
																			return [datasets.SplitGenerator(name=datasets.Split.TRAIN	,  gen_kwargs={"files": files}     )]
												__UpperCAmelCase						:			Union[str, Any]         =   []
												for split_name, files in data_files.items():
																			if isinstance(__lowerCamelCase	,  __lowerCamelCase     ):
																										__UpperCAmelCase						:			Tuple         =   [files]
																			# Use `dl_manager.iter_files` to skip hidden files in an extracted archive
																			__UpperCAmelCase						:			List[Any]         =   [dl_manager.iter_files(__lowerCamelCase     ) for file in files]
																			# Infer features is they are stoed in the arrow schema
																			if self.info.features is None:
																										for file in itertools.chain.from_iterable(__lowerCamelCase     ):
																																	with open(__lowerCamelCase	,  "rb"     ) as f:
																																								__UpperCAmelCase						:			Union[str, Any]         =   datasets.Features.from_arrow_schema(pa.ipc.open_stream(__lowerCamelCase     ).schema     )
																																	break
																			splits.append(datasets.SplitGenerator(name=__lowerCamelCase	,  gen_kwargs={"files": files}     )     )
												return splits
					def    _lowerCamelCase (  self:				str	,  __lowerCamelCase:				pa.Table     )    ->				pa.Table:
												if self.info.features is not None:
																			# more expensive cast to support nested features with keys in a different order
																			# allows str <-> int/float or str to Audio for example
																			__UpperCAmelCase						:			List[str]         =   table_cast(__lowerCamelCase	,  self.info.features.arrow_schema     )
												return pa_table





					def    _lowerCamelCase (  self:				Any	,  __lowerCamelCase:				Any     )    ->				Any:
												for file_idx, file in enumerate(itertools.chain.from_iterable(__lowerCamelCase     )     ):
																			with open(__lowerCamelCase	,  "rb"     ) as f:
																										try:
																																	for batch_idx, record_batch in enumerate(pa.ipc.open_stream(__lowerCamelCase     )     ):
																																								__UpperCAmelCase						:			Optional[int]         =   pa.Table.from_batches([record_batch]     )
																																								# Uncomment for debugging (will print the Arrow table size and elements)
																																								# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
																																								# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
																																								yield f'''{file_idx}_{batch_idx}''', self._cast_table(__lowerCamelCase     )
																										except ValueError as e:
																																	logger.error(f'''Failed to read file \'{file}\' with error {type(__lowerCamelCase     )}: {e}'''     )
																																	raise




